Skip to content

Commit b3ef4e3

Browse files
committed
Refactored code by moving common function to base class
1 parent 5688869 commit b3ef4e3

File tree

4 files changed

+51
-47
lines changed

4 files changed

+51
-47
lines changed

lib/open_weather_api.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ module OpenWeather
22
$LOAD_PATH<< "../lib"
33

44
autoload :Base, "open_weather_api/base"
5-
autoload :Current, "open_weather_api/current_weather"
5+
autoload :Current, "open_weather_api/current"
6+
autoload :Forecast, "open_weather_api/forecast"
67
autoload :VERSION, "open_weather_api/version"
78

89
require "open_weather_api/api.rb"

lib/open_weather_api/base.rb

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,49 @@
11
require 'httparty'
22
require 'addressable/uri'
3+
34
module OpenWeather
45
class Base
5-
def self.send_request(request)
6+
7+
attr_reader :url, :options, :weather_info, :status, :message
8+
9+
def initialize url, options
10+
@status = false
11+
@url = url
12+
@options = extract_options!(options)
13+
end
14+
15+
def retrive
16+
@response = send_request(self) unless @options.empty?
17+
parse_response if @response
18+
end
19+
20+
def success?
21+
@status == 200
22+
end
23+
24+
private
25+
26+
def extract_options!(options)
27+
valid_options = [:lat, :lon, :city, :country, :id]
28+
options.keys.each { |k| options.delete(k) unless valid_options.include?(k) }
29+
30+
if options[:city] || options[:country]
31+
options[:q] = "#{options[:country]},#{options[:city]}"
32+
options.delete(:city)
33+
options.delete(:country)
34+
end
35+
36+
options
37+
end
38+
39+
def parse_response
40+
@weather_info = @response
41+
@status = @weather_info["cod"]
42+
@message = @weather_info["message"] unless @status
43+
@weather_info
44+
end
45+
46+
def send_request(request)
647
uri = Addressable::URI.parse(request.url)
748
uri.query_values = request.options
849
HTTParty.get(uri.to_s)

lib/open_weather_api/current.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module OpenWeather
2+
class Current < Base
3+
def initialize(options = {})
4+
super("http://api.openweathermap.org/data/2.5/weather", options)
5+
end
6+
end
7+
end

lib/open_weather_api/current_weather.rb

Lines changed: 0 additions & 45 deletions
This file was deleted.

0 commit comments

Comments
 (0)