Module: JSONCache::FileCache

Extended by:
FileCache
Included in:
FileCache
Defined in:
lib/jsoncache/filecache.rb

Overview

This module provides an easy to use class method cache which caches json in a key-value fashion to the filesystem in /tmp/jsoncache.

Constant Summary collapse

CACHE_DIR =
'/tmp/jsoncache'.freeze

Instance Method Summary collapse

Instance Method Details

#cache(*key, expiry: 0) ⇒ Object

Retrieves cached data for the specified key and caches the data provided if the cache isn’t valid. Specify a code block after the method call that returns a hash and it will be cached.

Parameters

key

String The key in which to check for cached data.

options

Hash A hash of the parameters to use when caching.

Options

Accepted options

:symbolize

Boolean Symbolize keys while parsing JSON.

:cache_directory

String The folder name in /tmp to use as the cache.

:expiry

Fixnum The validity time of the cache in seconds.

Examples

def get_response(uri)
  JSONCache.cache(uri_to_key(uri), expiry: 120) do
    query_some_json_api(uri)
  end
end


36
37
38
39
40
41
42
# File 'lib/jsoncache/filecache.rb', line 36

def cache(*key, expiry: 0)
  normalized_key = normalize(key)
  return retrieve_cache(normalized_key) if cached?(normalized_key, expiry)
  result = yield
  cache_file(normalized_key, result)
  result
end