Class: Forecast::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/forecast/http.rb

Instance Method Summary collapse

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(options = {})
  @options = {cache: nil}.merge options
  if @options[:cache]
    cache_options = @options[:cache].merge({
      host: "127.0.0.1", 
      port: "6379"
    })
    if cache_options.has_key?(:url)
      url = cache_options[: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: cache_options[:host], port: cache_options[: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 && (!@options[:cache].has_key?(:invalidate) || !@options[: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 @options[:cache] && @options[:cache].has_key?(:expire)
        @cache.expire(key, @options[: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