Class: BasicCache::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/caches/cache.rb

Overview

Cache object, maintains a key/value store

Direct Known Subclasses

TimeCache

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#storeObject (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)

Returns:

  • (Boolean)


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

#pruneObject

Prunes invalid/expired keys (a noop for the basic cache)



67
68
69
# File 'lib/caches/cache.rb', line 67

def prune
  []
end

#sizeObject

Return the size of the cache



25
26
27
# File 'lib/caches/cache.rb', line 25

def size
  @store.size
end