Advertisement
Guest User

Untitled

a guest
Sep 29th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. # weather.rb
  2. class Weather
  3. # Usage---
  4. # Controller: @weather = Weather::CurrentWeather.new(request).snapshot
  5. # View: render 'shared/weather/snapshot', snapshot: @weather
  6.  
  7. WEATHER_KEY = Rails.application.secrets.open_weather_map_key
  8. WEATHER_ENDPOINT = Rails.application.secrets.open_weather_map_url
  9.  
  10. def initialize(request)
  11. ip_address = request.remote_ip.to_s
  12. @location = Geocoder.search(ip_address).first
  13. end
  14.  
  15. def snapshot
  16. Weather::Snapshot.new(get_weather)
  17. end
  18.  
  19. private
  20.  
  21. def get_weather
  22. JSON.parse(RestClient.get(WEATHER_ENDPOINT, params: weather_options))
  23. end
  24.  
  25. def weather_options
  26. Hash.new.tap do |h|
  27. h[:appid] = WEATHER_KEY
  28. h[:lat] = @location.latitude
  29. h[:lon] = @location.longitude
  30. end
  31. end
  32.  
  33. end
  34.  
  35. # weather/snapshot.rb
  36. class Weather::Snapshot
  37. attr_reader :conditions, :description, :sun, :temperature, :windspeed
  38.  
  39. def initialize(weather_json)
  40. @conditions = weather_json['weather'][0]['main']
  41. @description = weather_json['weather'][0]['description']
  42. @sun = solar_hash(weather_json)
  43. @temperature = temperature_hash(weather_json)
  44. @windspeed = weather_json['wind']['speed']
  45. end
  46.  
  47. def sun(rise_or_set)
  48. Time.at(@sun[rise_or_set]).in_time_zone(Time.zone.name).
  49. strftime('%b %e at %l:%M%P')
  50. end
  51.  
  52. private
  53.  
  54. def kelvin_to_fahrenheit(kelvin_value)
  55. (kelvin_value * 9/5 - 459.67).round
  56. end
  57.  
  58. def solar_hash(weather_json)
  59. Hash.new.tap do |h|
  60. h[:set] = weather_json['sys']['sunset']
  61. h[:rise] = weather_json['sys']['sunrise']
  62. end
  63. end
  64.  
  65. def temperature_hash(weather_json)
  66. Hash.new.tap do |h|
  67. h[:current] = kelvin_to_fahrenheit(weather_json['main']['temp'])
  68. h[:high] = kelvin_to_fahrenheit(weather_json['main']['temp_max'])
  69. h[:low] = kelvin_to_fahrenheit(weather_json['main']['temp_min'])
  70. end
  71. end
  72.  
  73. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement