class WeatherSage::HTTP::Cache

HTTP cache backed by file.

Attributes

path[RW]

Public Class Methods

new(path, log, timeout = 30 * 60) click to toggle source

Create an HTTP cache backed by file at path where entries are valid for timeout seconds.

timeout defaults to 30 minutes if unspecified.

# File lib/weather-sage/http/cache.rb, line 13
def initialize(path, log, timeout = 30 * 60)
  @path, @log, @timeout = path.freeze, log, timeout
  @cache = ::WeatherSage::Cache.new(@path)
  @fetcher = ::WeatherSage::HTTP::Fetcher.new(@log)
  @parser = ::WeatherSage::HTTP::Parser.new(@log)
end

Public Instance Methods

get(url, params = {}) click to toggle source

Get cached URL, or request it if it is not cached.

# File lib/weather-sage/http/cache.rb, line 23
def get(url, params = {})
  # parse URL into URI, get key
  uri = make_uri(url, params)
  str = uri.to_s

  @log.debug('HTTP::Cache#get') { '%s' % [str] }

  unless r = @cache.get(str)
    # fetch response, parse body, and cache result
    r = @cache.set(str, parse(fetch(uri)), @timeout)
  end

  # return result
  r
end
key?(url, params = {}) click to toggle source

Returns true if the given URL in the cache.

# File lib/weather-sage/http/cache.rb, line 42
def key?(url, params = {})
  @cache.key?(make_uri(url, params).to_s)
end

Private Instance Methods

fetch(uri) click to toggle source

Fetch URI, and return response.

Raises an WeatherSage::HTTP::Error on error.

# File lib/weather-sage/http/cache.rb, line 62
def fetch(uri)
  @fetcher.fetch(uri)
end
make_uri(url, params = {}) click to toggle source

Convert a URL and parameters to a URI.

# File lib/weather-sage/http/cache.rb, line 51
def make_uri(url, params = {})
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(params) if params.size > 0
  uri
end
parse(resp) click to toggle source

Parse HTTP response body.

# File lib/weather-sage/http/cache.rb, line 69
def parse(resp)
  @parser.parse(resp)
end