Class: Backend::Cells::WeatherCellsController

Inherits:
BaseController show all
Defined in:
app/controllers/backend/cells/weather_cells_controller.rb

Instance Attribute Summary

Attributes inherited from ApplicationController

#current_theme

Instance Method Summary collapse

Methods inherited from BaseController

account_lettering_states_crit, accounts_range_crit, amount_range_crit, crit_params, journal_entries_states_crit, journal_letter_crit, journal_period_crit, journals_crit, search_conditions

Methods inherited from ApplicationController

#after_sign_in_path_for, #authorized?, human_action_name, #human_action_name, #session_controller?

Instance Method Details

#showObject


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/controllers/backend/cells/weather_cells_controller.rb', line 4

def show
  @forecast = nil
  openweathermap_api_key = Identifier.find_by(nature: :openweathermap_api_key)

  coordinates = params[:centroid]
  
  # We try to get weather from cultivable zones
  coordinates ||= CultivableZone.geom_union(:shape).centroid

  if coordinates.present? && openweathermap_api_key
    http = Net::HTTP.new('api.openweathermap.org')
    http.open_timeout = 3
    http.read_timeout = 3
    res = http.get("/data/2.5/forecast/daily?lat=#{coordinates.first}&lon=#{coordinates.second}&cnt=14&mode=json&APPID=#{openweathermap_api_key.value}")

    json = begin
             JSON.parse(res.body)
           rescue
             nil
           end
    unless json.nil?
      @forecast = json.deep_symbolize_keys
      if @forecast[:cod] == '200'
        @forecast[:list] = @forecast[:list].collect do |day|
          day.deep_symbolize_keys!
          {
            at: Time.zone.at(day[:dt]),
            temperatures: %i[day night min max eve morn].each_with_object({}) do |key, hash|
              hash[key] = (day[:temp][key] || 0).in_kelvin
              hash
            end,
            pressure: day[:pressure].in_hectopascal,
            humidity: (day[:humidity] || 0).in_percent,
            wind_speed: (day[:speed] || 0).in_meter_per_second,
            wind_direction: (day[:deg] || 0).in_degree,
            rain: (day[:rain] || 0).in_millimeter,
            clouds: (day[:rain] || 0).in_percent,
            # weather: day[:weather]
          }
        end
      else
        @forecast = nil
      end
    end
  elsif !openweathermap_api_key
    @forecast = nil
    logger.warn 'Missing OpenWeatherMap api key in identifiers)'
  end
rescue Net::OpenTimeout => e
  @forecast = nil
  logger.warn "Net::OpenTimeout: Cannot open service OpenWeatherMap in time (#{e.message})"
rescue Net::ReadTimeout => e
  @forecast = nil
  logger.warn "Net::ReadTimeout: Cannot read service OpenWeatherMap in time (#{e.message})"
end