Class: Forecast::Http
- Inherits:
-
Object
- Object
- Forecast::Http
- Defined in:
- lib/forecast/http.rb
Instance Method Summary collapse
- #get(url, params = {}) ⇒ Object
- #get_dom(url, params = {}) ⇒ Object
- #get_json(url, params = {}) ⇒ Object
-
#initialize(options = {}) ⇒ Http
constructor
A new instance of Http.
Constructor Details
#initialize(options = {}) ⇒ Http
Returns a new instance of Http.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/forecast/http.rb', line 11 def initialize( = {}) = {cache: nil}.merge if [:cache] = [:cache].merge({ host: "127.0.0.1", port: "6379" }) if .has_key?(:url) url = [:url] uri = URI.parse(url) #puts "Connecting to redis with url #{url}..." @cache = Redis.new(host: uri.host, port: uri.port, password: uri.password) elsif host != nil && port != nil #puts "Connecting to redis on host #{host} at port #{port}..." @cache = Redis.new(host: [:host], port: [:port]) end end end |
Instance Method Details
#get(url, params = {}) ⇒ Object
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 |
# File 'lib/forecast/http.rb', line 30 def get(url, params = {}) if @cache && (![:cache].has_key?(:invalidate) || ![:cache][:invalidate]) key = get_key(url) data = @cache.get(key) if data #puts 'Read from cache... ' + url return data end end if params.keys.count > 0 query_string = URI.encode_www_form(params) url = url + "?" + query_string end #puts 'Get url... ' + url resp = Net::HTTP.get_response(URI.parse(url)) data = resp.body if data if @cache #puts 'Write to cache... ' + url key = get_key(url) @cache.set(key, data) if [:cache] && [:cache].has_key?(:expire) @cache.expire(key, [:cache][:expire]) end end return data end end |
#get_dom(url, params = {}) ⇒ Object
66 67 68 69 70 71 |
# File 'lib/forecast/http.rb', line 66 def get_dom(url, params = {}) data = get(url, params) if data != nil return REXML::Document.new(data) end end |
#get_json(url, params = {}) ⇒ Object
59 60 61 62 63 64 |
# File 'lib/forecast/http.rb', line 59 def get_json(url, params = {}) data = get(url, params) if data != nil return JSON.parse(data) end end |