Class: BasicCache::Cache
- Inherits:
-
Object
- Object
- BasicCache::Cache
- Defined in:
- lib/caches/cache.rb
Overview
Cache object, maintains a key/value store
Direct Known Subclasses
Instance Attribute Summary collapse
-
#store ⇒ Object
readonly
Returns the value of attribute store.
Instance Method Summary collapse
-
#[](key = nil) ⇒ Object
Retrieve cached value.
-
#cache(key = nil, &code) ⇒ Object
If the key is cached, return it.
-
#clear!(key = nil) ⇒ Object
Empty out either the given key or the full store.
-
#include?(key = nil) ⇒ Boolean
Check if a value is cached (just a wrapper, designed to be redefined by subclasses).
-
#initialize(params = {}) ⇒ Cache
constructor
Generate an empty store.
-
#prune ⇒ Object
Prunes invalid/expired keys (a noop for the basic cache).
-
#size ⇒ Object
Return the size of the cache.
Constructor Details
#initialize(params = {}) ⇒ Cache
Generate an empty store
17 18 19 20 |
# File 'lib/caches/cache.rb', line 17 def initialize(params = {}) params = { store: params } unless params.is_a? Hash @store = params.fetch(:store) { BasicCache::DEFAULT_STORE.new } end |
Instance Attribute Details
#store ⇒ Object (readonly)
Returns the value of attribute store.
12 13 14 |
# File 'lib/caches/cache.rb', line 12 def store @store end |
Instance Method Details
#[](key = nil) ⇒ Object
Retrieve cached value
50 51 52 53 54 |
# File 'lib/caches/cache.rb', line 50 def [](key = nil) key ||= BasicCache.caller_name fail KeyError, 'Key not cached' unless include? key.to_sym @store[key.to_sym] end |
#cache(key = nil, &code) ⇒ Object
If the key is cached, return it. If not, run the code, cache the result, and return it
33 34 35 36 |
# File 'lib/caches/cache.rb', line 33 def cache(key = nil, &code) key ||= BasicCache.caller_name @store[key.to_sym] ||= code.call end |
#clear!(key = nil) ⇒ Object
Empty out either the given key or the full store
59 60 61 62 |
# File 'lib/caches/cache.rb', line 59 def clear!(key = nil) key = key.to_sym unless key.nil? @store.clear! key end |
#include?(key = nil) ⇒ Boolean
Check if a value is cached (just a wrapper, designed to be redefined by subclasses)
42 43 44 45 |
# File 'lib/caches/cache.rb', line 42 def include?(key = nil) key ||= BasicCache.caller_name @store.include? key.to_sym end |
#prune ⇒ Object
Prunes invalid/expired keys (a noop for the basic cache)
67 68 69 |
# File 'lib/caches/cache.rb', line 67 def prune [] end |
#size ⇒ Object
Return the size of the cache
25 26 27 |
# File 'lib/caches/cache.rb', line 25 def size @store.size end |