Skip to content

Instantly share code, notes, and snippets.

@jerry
Created September 20, 2010 19:38
Show Gist options
  • Save jerry/588519 to your computer and use it in GitHub Desktop.
Save jerry/588519 to your computer and use it in GitHub Desktop.
Make It Rain
# db/migrations/20090204131104_create_forecasts.rb
class CreateForecasts < ActiveRecord::Migration
def self.up
create_table :forecasts do |t|
t.string :f_text, :f_period, :image, :weather, :temp
t.timestamps
end
end
def self.down
drop_table :forecasts
end
end
# in a layout or the front page
<% fc = Forecast.first %>
<% unless fc.nil? %><br/>
<h3><%= link_to "#{fc.f_period} in Sebring", weather_path %>: <%= fc.weather %> (<%= fc.temp %>&deg;)</h3>
<% end %>
# add to config/environment.rb
config.gem 'httparty'
# app/models/forecast.rb
require 'httparty'
class Forecast < ActiveRecord::Base
include HTTParty
ICON_LOCATION = "http://mobile.wrh.noaa.gov/weather/images/fcicons"
class << self
def check_date
Forecast.reload_forecasts if Forecast.count == 0 || Forecast.find(:first).created_at < 60.minutes.ago
end
# find your combo of cityname, state, site, etc. using http://forecast.weather.gov/ - use the "Text Only Forecast" link in the bottom right corner of the forecast page and change TextType from 1 to 3 to get the XML feed
def reload_forecasts
Forecast.delete_all
f_path = "http://forecast.weather.gov/MapClick.php?CityName=Sebring&state=FL&site=TBW&textField1=27.49070&textField2=-81.45350&TextType=3"
Forecast.get(f_path)["Forecast"]["period"].each do |fc|
Forecast.create!(:f_text => fc["text"], :f_period => fc["valid"], :image => fc["image"], :weather => fc["weather"], :temp => fc["temp"])
end
end
def all
Forecast.find(:all)
end
def first
Forecast.find(:first)
end
end
def icon
"#{ICON_LOCATION}/#{image}"
end
end
# add to config/routes.rb
map.weather "/weather", :controller => 'home', :action => 'weather'
# weather.html.erb
<h1>Weather Forecast for Sebring, FL</h1>
<h5>Last updated: <%= @forecasts.first.created_at.to_s(:short) %></h5>
<% @forecasts.each do |fc| %>
<div class="forecast">
<h2><%= image_tag fc.icon, :align => "right", :alt => fc.weather %><%= fc.f_period %> (<%= fc.temp %>&deg;)</h2>
<p><%= fc.f_text %></p>
</div>
<% end %>
<%# list of loops available at http://radar.weather.gov/Conus/Loop/ %>
<%= image_tag "http://radar.weather.gov/Conus/Loop/southeast_loop.gif", :style => "width: 540px; height: 700px;" %>
# lib/tasks/weather.rake
namespace :weather do
desc "Get latest Forecasts"
task :forecasts => :environment do
Forecast.check_date
end
end
# using 'crontab -e' on the server, add the following line
# 11,41 * * * * cd /sites/site_name_here/current && /usr/bin/rake RAILS_ENV=production weather:forecasts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment