ababup1192
6/27/2017 - 8:09 AM

main.rb

require 'net/http'
require 'json'
require_relative './open_weather_map'
require_relative './weather'

# Access for OpenWeatherMap API
class WeatherAPI
  def initialize(key)
    @key = key
  end

  def weather(place)
    uri = URI.parse(OpenWeatherMap::BASE_URI + query(place))
    json = Net::HTTP.get(uri)
    hash = JSON.parse(json, symbolize_names: true)
    now = hash[:list][0]

    now[:weather].map do |h|
      Weather.new(
        h[:main], h[:description], h[:icon], now[:dt_txt]
      )
    end
  end

  private

  def query(place)
    "?q=#{place},jp&APPID=#{OpenWeatherMap::KEY}"
  end
end
# Weather Object for OpenWeatherAPI
class Weather
  attr_reader :main, :description, :icon, :date_time

  def initialize(main, description, icon, date_time)
    @main = main
    @description = description
    @icon = icon
    @date_time = date_time
  end
end
# Constants for OpenWeatherMap
module OpenWeatherMap
  KEY = '3e69a122994192dbd9ef5e624d19b162'.freeze
  BASE_URI = 'http://api.openweathermap.org/data/2.5/forecast'.freeze
end
require_relative './weather_api'
require_relative './open_weather_map'

api = WeatherAPI.new(OpenWeatherMap::KEY)
api.weather('Tokyo')