class Weatherfor::ApiConsultant

Make the API request and parse data

Attributes

obj[R]

Public Class Methods

new(city, api_id) click to toggle source
# File lib/weatherfor.rb, line 14
def initialize(city, api_id)
  uri = url(city, api_id)
  res = Net::HTTP.get_response(uri)

  @obj = case res.code
         when '200'
           JSON.parse(res.body)
         else
           { error: res.message }
         end
end

Public Instance Methods

avg_temp_in_days() click to toggle source
# File lib/weatherfor.rb, line 33
def avg_temp_in_days
  @arr = []
  obj['list'].group_by { |item| Time.at(item['dt']).strftime('%m-%d-%Y') }.each do |date, data|
    avg_temp = data.sum { |info| info['main']['temp'] }
    avg_temp /= data.count
    @arr << { avg_temp: avg_temp, date: date }
  end
end
city_name() click to toggle source
# File lib/weatherfor.rb, line 46
def city_name
  obj['city']['name']
end
current_date() click to toggle source
# File lib/weatherfor.rb, line 54
def current_date
  Time.now.strftime('%d/%m')
end
current_temp_desc() click to toggle source
# File lib/weatherfor.rb, line 50
def current_temp_desc
  obj['list'][0]['weather'][0]['description']
end
today_avg_temp() click to toggle source
# File lib/weatherfor.rb, line 42
def today_avg_temp
  obj['list'][0]['main']['temp'].round
end
weather_in_days() click to toggle source
# File lib/weatherfor.rb, line 26
def weather_in_days
  avg_temp_in_days

  "#{today_avg_temp}°C e #{current_temp_desc} em #{city_name} em #{current_date}." \
    " Média para os próximos dias: #{parse_avg_text}"
end

Private Instance Methods

parse_avg_text() click to toggle source
# File lib/weatherfor.rb, line 60
def parse_avg_text
  text = ''
  @arr.last(5).each_with_index do |item, index|
    text += "#{item[:avg_temp].round(0)}°C em #{parse_date(item[:date])}"
    text += ', ' if index <= 2
    text += ' e ' if index == 3
    text += '.' if index == 4
  end
  text
end
parse_date(date) click to toggle source
# File lib/weatherfor.rb, line 71
def parse_date(date)
  date.gsub('-', '/').delete_suffix('/2021')
end
url(city, api_id) click to toggle source
# File lib/weatherfor.rb, line 75
def url(city, api_id)
  URI("https://api.openweathermap.org/data/2.5/forecast?q=#{city}&appid=#{api_id}&lang=pt_br&units=metric")
end