class Forecast::Http

Public Class Methods

new(options = {}) click to toggle source
# 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

Public Instance Methods

get(url, params = {}) click to toggle source
# 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 = {}) click to toggle source
# 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 = {}) click to toggle source
# 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

Private Instance Methods

get_key(url) click to toggle source
# File lib/forecast/http.rb, line 75
def get_key(url)
  "Forecast::Http::" + url
end