Class: BasicCache::TimeCache
Overview
Time-based cache object
Instance Attribute Summary collapse
-
#lifetime ⇒ Object
readonly
Returns the value of attribute lifetime.
Attributes inherited from Cache
Instance Method Summary collapse
-
#[](key = nil) ⇒ Object
Retrieve a value.
-
#cache(key = nil, &code) ⇒ Object
Return a value from the cache, or calculate it and store it Recalculate if the cached value has expired.
-
#clear!(key = nil) ⇒ Object
Remove a value, or clear the cache.
-
#include?(key = nil) ⇒ Boolean
Check if a value is cached and not expired.
-
#initialize(params = {}) ⇒ TimeCache
constructor
Generate an empty store, with a default lifetime of 60 seconds.
-
#prune ⇒ Object
Prune expired keys.
-
#size ⇒ Object
Return the size of the cache (don’t include expired entries).
Constructor Details
#initialize(params = {}) ⇒ TimeCache
Generate an empty store, with a default lifetime of 60 seconds
17 18 19 20 21 |
# File 'lib/caches/timecache.rb', line 17 def initialize(params = {}) params = { store: params } unless params.is_a? Hash @lifetime = params.fetch :lifetime, 60 super end |
Instance Attribute Details
#lifetime ⇒ Object (readonly)
Returns the value of attribute lifetime.
12 13 14 |
# File 'lib/caches/timecache.rb', line 12 def lifetime @lifetime end |
Instance Method Details
#[](key = nil) ⇒ Object
Retrieve a value
53 54 55 |
# File 'lib/caches/timecache.rb', line 53 def [](key = nil) super.value end |
#cache(key = nil, &code) ⇒ Object
Return a value from the cache, or calculate it and store it Recalculate if the cached value has expired
34 35 36 37 38 39 |
# File 'lib/caches/timecache.rb', line 34 def cache(key = nil, &code) key ||= BasicCache.caller_name key = key.to_sym @store[key] = TimeCacheItem.new(Time.now, code.call) unless include? key @store[key].value end |
#clear!(key = nil) ⇒ Object
Remove a value, or clear the cache
60 61 62 63 |
# File 'lib/caches/timecache.rb', line 60 def clear!(key = nil) resp = super resp.class == TimeCacheItem ? resp.value : resp end |
#include?(key = nil) ⇒ Boolean
Check if a value is cached and not expired
44 45 46 47 48 |
# File 'lib/caches/timecache.rb', line 44 def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end |
#prune ⇒ Object
Prune expired keys
68 69 70 |
# File 'lib/caches/timecache.rb', line 68 def prune @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k } end |
#size ⇒ Object
Return the size of the cache (don’t include expired entries)
26 27 28 |
# File 'lib/caches/timecache.rb', line 26 def size @store.keys.count { |k| Time.now - @store[k].stamp < @lifetime } end |