Module: JSONCache

Extended by:
JSONCache
Included in:
JSONCache
Defined in:
lib/jsoncache.rb

Overview

JSONCache is a simple interface to cache JSON based API calls

Author

Derek Stride ([email protected])

License

MIT

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

Instance Method Summary collapse

Instance Method Details

#cache(key, options = {}) ⇒ 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.

:delta

Fixnum The validity time of the cache in seconds.

Examples

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


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

def cache(key, options = {})
  return retrieve_cache(key, options) if cached?(key, options)
  result = yield
  cache_file(key, result, options)
  result
end