weather_agent.rb 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. require 'date'
  2. require 'cgi'
  3. module Agents
  4. class WeatherAgent < Agent
  5. cannot_receive_events!
  6. description <<-MD
  7. The WeatherAgent creates an event for the following day's weather at a given `location`.
  8. The `location` can be a US zipcode, or any location that Wunderground supports. To find one, search [wunderground.com](http://wunderground.com) and copy the location part of the URL. For example, a result for San Francisco gives `http://www.wunderground.com/US/CA/San_Francisco.html` and London, England gives `http://www.wunderground.com/q/zmw:00000.1.03772`. The locations in each are `US/CA/San_Francisco` and `zmw:00000.1.03772`, respectively.
  9. You must setup an [API key for Wunderground](http://www.wunderground.com/weather/api/) in order to use this Agent.
  10. MD
  11. event_description <<-MD
  12. Events look like this:
  13. {
  14. "location": 12345,
  15. "date": {
  16. "epoch": "1357959600",
  17. "pretty": "10:00 PM EST on January 11, 2013"
  18. },
  19. "high": {
  20. "fahrenheit": "64",
  21. "celsius": "18"
  22. },
  23. "low": {
  24. "fahrenheit": "52",
  25. "celsius": "11"
  26. },
  27. "conditions": "Rain Showers",
  28. "icon": "rain",
  29. "icon_url": "http://icons-ak.wxug.com/i/c/k/rain.gif",
  30. "skyicon": "mostlycloudy",
  31. ...
  32. }
  33. MD
  34. default_schedule "8pm"
  35. def working?
  36. event_created_within?(2) && !recent_error_logs?
  37. end
  38. def wunderground
  39. Wunderground.new(options['api_key']) if key_setup?
  40. end
  41. def key_setup?
  42. options['api_key'] && options['api_key'] != "your-key"
  43. end
  44. def default_options
  45. {
  46. 'api_key' => "your-key",
  47. 'location' => "94103"
  48. }
  49. end
  50. def validate_options
  51. errors.add(:base, "location is required") unless options['location'].present? || options['zipcode'].present?
  52. errors.add(:base, "api_key is required") unless options['api_key'].present?
  53. end
  54. def check
  55. if key_setup?
  56. wunderground.forecast_for(options['location'] || options['zipcode'])["forecast"]["simpleforecast"]["forecastday"].each do |day|
  57. if is_tomorrow?(day)
  58. create_event :payload => day.merge('location' => options['location'] || options['zipcode'])
  59. end
  60. end
  61. end
  62. end
  63. def is_tomorrow?(day)
  64. Time.zone.at(day["date"]["epoch"].to_i).to_date == Time.zone.now.tomorrow.to_date
  65. end
  66. end
  67. end