Class: Tropical::OpenWeatherMap

Inherits:
Object
  • Object
show all
Defined in:
lib/tropical.rb

Constant Summary collapse

BASE_URL =
"https://api.openweathermap.org/data/2.5/forecast?".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ OpenWeatherMap

Returns a new instance of OpenWeatherMap.



14
15
16
17
18
19
# File 'lib/tropical.rb', line 14

def initialize(params)
  @params  = params
  response = post(request_params)

  load_data(response)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



12
13
14
# File 'lib/tropical.rb', line 12

def data
  @data
end

#paramsObject (readonly)

Returns the value of attribute params.



12
13
14
# File 'lib/tropical.rb', line 12

def params
  @params
end

#statusObject (readonly)

Returns the value of attribute status.



12
13
14
# File 'lib/tropical.rb', line 12

def status
  @status
end

Instance Method Details

#average_temp_by_daysObject



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/tropical.rb', line 75

def average_temp_by_days
  group_by_days = list.group_by { |item| item[:dt].to_date }
  days = []

  group_by_days.each do |day, temps|
    average = temps.sum { |time| time[:temp] } / temps.length

    days << { day: day, average: average.round }
  end

  days
end

#cityObject



21
22
23
# File 'lib/tropical.rb', line 21

def city
  data["city"]["name"]
end

#current_dateObject



25
26
27
# File 'lib/tropical.rb', line 25

def current_date
  list.first[:dt]
end

#current_tempObject



29
30
31
# File 'lib/tropical.rb', line 29

def current_temp
  list.first[:temp]
end

#current_weatherObject



33
34
35
# File 'lib/tropical.rb', line 33

def current_weather
  list.first[:description]
end

#full_sumaryObject



46
47
48
49
50
# File 'lib/tropical.rb', line 46

def full_sumary
  "#{sumary_current_day} "\
  "Média para os próximos dias: "\
  "#{sumary_days_forecast}"
end

#listObject



65
66
67
68
69
70
71
72
73
# File 'lib/tropical.rb', line 65

def list
  data["list"].map do |list_item|
    {
      dt: Time.at(list_item["dt"]),
      temp: list_item["main"]["temp"],
      description: list_item["weather"].first["description"]
    }
  end
end

#scaleObject



37
38
39
40
41
42
43
44
# File 'lib/tropical.rb', line 37

def scale
  units = params[:units]

  return "°C" if units == "metric"
  return "°F" if units == "imperial"

  "°K"
end

#sumary_current_dayObject



52
53
54
55
# File 'lib/tropical.rb', line 52

def sumary_current_day
  "#{current_temp.round}#{scale} e #{current_weather} em "\
  "#{city} em #{current_date.strftime("%d/%m")}."
end

#sumary_days_forecastObject



57
58
59
60
61
62
63
# File 'lib/tropical.rb', line 57

def sumary_days_forecast
  list = average_temp_by_days.map do |x|
    "#{x[:average]}#{scale} em #{x[:day].strftime("%d/%m")}"
  end

  "#{list.to_sentence(words_connector: ", ", last_word_connector: " e ")}."
end