Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # weather.rb
- class Weather
- # Usage---
- # Controller: @weather = Weather::CurrentWeather.new(request).snapshot
- # View: render 'shared/weather/snapshot', snapshot: @weather
- WEATHER_KEY = Rails.application.secrets.open_weather_map_key
- WEATHER_ENDPOINT = Rails.application.secrets.open_weather_map_url
- def initialize(request)
- ip_address = request.remote_ip.to_s
- @location = Geocoder.search(ip_address).first
- end
- def snapshot
- Weather::Snapshot.new(get_weather)
- end
- private
- def get_weather
- JSON.parse(RestClient.get(WEATHER_ENDPOINT, params: weather_options))
- end
- def weather_options
- Hash.new.tap do |h|
- h[:appid] = WEATHER_KEY
- h[:lat] = @location.latitude
- h[:lon] = @location.longitude
- end
- end
- end
- # weather/snapshot.rb
- class Weather::Snapshot
- attr_reader :conditions, :description, :sun, :temperature, :windspeed
- def initialize(weather_json)
- @conditions = weather_json['weather'][0]['main']
- @description = weather_json['weather'][0]['description']
- @sun = solar_hash(weather_json)
- @temperature = temperature_hash(weather_json)
- @windspeed = weather_json['wind']['speed']
- end
- def sun(rise_or_set)
- Time.at(@sun[rise_or_set]).in_time_zone(Time.zone.name).
- strftime('%b %e at %l:%M%P')
- end
- private
- def kelvin_to_fahrenheit(kelvin_value)
- (kelvin_value * 9/5 - 459.67).round
- end
- def solar_hash(weather_json)
- Hash.new.tap do |h|
- h[:set] = weather_json['sys']['sunset']
- h[:rise] = weather_json['sys']['sunrise']
- end
- end
- def temperature_hash(weather_json)
- Hash.new.tap do |h|
- h[:current] = kelvin_to_fahrenheit(weather_json['main']['temp'])
- h[:high] = kelvin_to_fahrenheit(weather_json['main']['temp_max'])
- h[:low] = kelvin_to_fahrenheit(weather_json['main']['temp_min'])
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement