-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathbase.rb
More file actions
57 lines (45 loc) · 1.34 KB
/
base.rb
File metadata and controls
57 lines (45 loc) · 1.34 KB
1
2
3
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
require 'net/http'
require 'json'
module OpenWeather
class Base
API_URL = 'https://api.openweathermap.org/data/2.5'
attr_reader :url, :options, :weather_info, :status, :message
def initialize(url, options)
@status = false
@url = url
@options = extract_options!(options)
end
def retrieve(url=nil)
response = send_request url unless @options.empty?
parse_response(response)
end
def success?
@status == 200
end
private
def extract_options!(options)
valid_options = [ :id, :lat, :lon, :cnt, :city, :lang, :units, :APPID,
:country, :bbox, :q, :type, :start, :end]
options.keys.each { |k| options.delete(k) unless valid_options.include?(k) }
if options[:city] || options[:country]
options[:q] = "#{options[:country]},#{options[:city]}"
options.delete(:city)
options.delete(:country)
end
options
end
def parse_response(response)
return if response.nil?
@weather_info = JSON.parse(response)
@status = @weather_info['cod']
@message = @weather_info['message'] unless @status
@weather_info
end
def send_request(url=nil)
url = url || @url
uri = URI(url)
uri.query = URI.encode_www_form(options)
Net::HTTP.get(uri)
end
end
end