Class: Hoodie::Stash::Cache

Inherits:
Object show all
Defined in:
lib/hoodie/stash/cache.rb

Overview

Disk stashing method variable caching hash, string, array store.

Key/value cache store

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Cache

Initializes a new empty store



33
34
35
36
# File 'lib/hoodie/stash/cache.rb', line 33

def initialize(params = {})
  params = { store: params } unless params.is_a? Hash
  @store = params.fetch(:store) { DEFAULT_STORE }
end

Instance Attribute Details

#:store(: store) ⇒ Stash (readonly)



29
# File 'lib/hoodie/stash/cache.rb', line 29

attr_reader :store

#storeObject (readonly)

Returns the value of attribute store.



29
30
31
# File 'lib/hoodie/stash/cache.rb', line 29

def store
  @store
end

Instance Method Details

#[](key = nil) ⇒ Hash, ...

Retrieves the value for a given key, if nothing is set, returns KeyError

Raises:

  • (KeyError)

    if no such key found



59
60
61
62
63
# File 'lib/hoodie/stash/cache.rb', line 59

def [](key = nil)
  key ||= Stash.caller_name
  fail KeyError, 'Key not cached' unless include? key.to_sym
  @store[key.to_sym]
end

#cache(key = nil, &code) ⇒ Hash, ...

Retrieves the value for a given key, if nothing is set, run the code, cache the result, and return it



73
74
75
76
# File 'lib/hoodie/stash/cache.rb', line 73

def cache(key = nil, &code)
  key ||= Stash.caller_name
  @store[key.to_sym] ||= code.call
end

#clear!(key = nil) ⇒ Object

Clear the whole stash store or the value of a key

clear.



45
46
47
48
# File 'lib/hoodie/stash/cache.rb', line 45

def clear!(key = nil)
  key = key.to_sym unless key.nil?
  @store.clear! key
end

#include?(key = nil) ⇒ Boolean

return a boolean indicating presence of the given key in the store



92
93
94
95
# File 'lib/hoodie/stash/cache.rb', line 92

def include?(key = nil)
  key ||= Stash.caller_name
  @store.include? key.to_sym
end

#sizeFixnum

return the size of the store as an integer



82
83
84
# File 'lib/hoodie/stash/cache.rb', line 82

def size
  @store.size
end