Class: WeatherSage::HTTP::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/weather-sage/http/cache.rb

Overview

HTTP cache backed by file.

Direct Known Subclasses

CLI::Env::Cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, log, timeout = 30 * 60) ⇒ Cache

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

timeout defaults to 30 minutes if unspecified.



13
14
15
16
17
18
# 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

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



5
6
7
# File 'lib/weather-sage/http/cache.rb', line 5

def path
  @path
end

Instance Method Details

#get(url, params = {}) ⇒ Object

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



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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 = {}) ⇒ Boolean

Returns true if the given URL in the cache.



42
43
44
# File 'lib/weather-sage/http/cache.rb', line 42

def key?(url, params = {})
  @cache.key?(make_uri(url, params).to_s)
end