weather_agent.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. require 'date'
  2. module Agents
  3. class WeatherAgent < Agent
  4. cannot_receive_events!
  5. description <<-MD
  6. The WeatherAgent creates an event for the following day's weather at `zipcode`.
  7. You must setup an API key for Wunderground in order to use this Agent.
  8. MD
  9. event_description <<-MD
  10. Events look like this:
  11. {
  12. :zipcode => 12345,
  13. :date => { :epoch=>"1357959600", :pretty=>"10:00 PM EST on January 11, 2013" },
  14. :high => { :fahrenheit=>"64", :celsius=>"18" },
  15. :low => { :fahrenheit=>"52", :celsius=>"11" },
  16. :conditions => "Rain Showers",
  17. :icon=>"rain",
  18. :icon_url => "http://icons-ak.wxug.com/i/c/k/rain.gif",
  19. :skyicon => "mostlycloudy",
  20. :pop => 80,
  21. :qpf_allday => { :in=>0.24, :mm=>6.1 },
  22. :qpf_day => { :in=>0.13, :mm=>3.3 },
  23. :qpf_night => { :in=>0.03, :mm=>0.8 },
  24. :snow_allday => { :in=>0, :cm=>0 },
  25. :snow_day => { :in=>0, :cm=>0 },
  26. :snow_night => { :in=>0, :cm=>0 },
  27. :maxwind => { :mph=>15, :kph=>24, :dir=>"SSE", :degrees=>160 },
  28. :avewind => { :mph=>9, :kph=>14, :dir=>"SSW", :degrees=>194 },
  29. :avehumidity => 85,
  30. :maxhumidity => 93,
  31. :minhumidity => 63
  32. }
  33. MD
  34. default_schedule "midnight"
  35. def working?
  36. (event = event_created_within(2.days)) && event.payload.present?
  37. end
  38. def wunderground
  39. Wunderground.new("your-api-key")
  40. end
  41. def default_options
  42. { :zipcode => "94103" }
  43. end
  44. def validate_options
  45. errors.add(:base, "zipcode is required") unless options[:zipcode].present?
  46. end
  47. def check
  48. wunderground.forecast_for(options[:zipcode])["forecast"]["simpleforecast"]["forecastday"].each do |day|
  49. if is_tomorrow?(day)
  50. create_event :payload => day.merge(:zipcode => options[:zipcode])
  51. end
  52. end
  53. end
  54. def is_tomorrow?(day)
  55. Time.zone.at(day["date"]["epoch"].to_i).to_date == Time.zone.now.tomorrow.to_date
  56. end
  57. end
  58. end