Module: JSONCache

Defined in:
lib/jsoncache.rb

Overview

JSONCache is a simple interface to cache JSON based API calls

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cache_directoryObject

Returns the value of attribute cache_directory.



5
6
7
# File 'lib/jsoncache.rb', line 5

def cache_directory
  @cache_directory
end

Instance Method Details

#cache_file(response, uri) ⇒ Object

Cache the result from the uri

Parameters:

  • response (Hash)

    the response to cache.

  • uri (String)

    the uri in which to check for a cached call.



25
26
27
28
29
30
31
32
33
# File 'lib/jsoncache.rb', line 25

def cache_file(response, uri)
  cache_path = cache_dir
  existing_file = filename_from_uri(uri)
  last_path = "#{cache_path}/#{existing_file}"
  File.delete(last_path) if existing_file && File.exist?(last_path)
  File.write(
    "#{cache_path}/#{uri_to_file_path_root(uri)}#{Time.now.to_i}.json",
    JSON.generate(response))
end

#cached?(uri, delta = 0) ⇒ Boolean

Determine whether a file is cached and healthy

Parameters:

  • uri (String)

    the uri in which to check for a cached call.

  • stale (boolean)

    whether or not a cached file can go stale.

  • delta (Fixnum) (defaults to: 0)

    the upperbound timestamp difference of a valid cache.

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
# File 'lib/jsoncache.rb', line 11

def cached?(uri, delta = 0)
  timestamp = timestamp_from_uri(uri)
  if timestamp.zero?
    false
  elsif !delta.zero?
    (Time.now.to_i - timestamp) < delta
  else
    true
  end
end

#retrieve_cache(uri, params = {}) ⇒ Object



35
36
37
38
39
# File 'lib/jsoncache.rb', line 35

def retrieve_cache(uri, params = {})
  JSON.parse(
    File.read("#{cache_dir}/#{filename_from_uri(uri)}"),
    params)
end