Class: Stash::Cache

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

Overview

Key/value cache store

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Cache

Initializes a new empty store



55
56
57
58
# File 'lib/hoodie/stash.rb', line 55

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

Instance Attribute Details

#storeHash (readonly)

Returns of the mem stash cache hash store.

Returns:

  • (Hash)

    of the mem stash cache hash store



51
52
53
# File 'lib/hoodie/stash.rb', line 51

def store
  @store
end

Instance Method Details

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

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

Parameters:

  • key (Symbol, String) (defaults to: nil)

    representing the key

Returns:

Raises:

  • (KeyError)

    if no such key found



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

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

Parameters:

  • key (Symbol, String) (defaults to: nil)

    representing the key

  • block (&block)

    that returns the value to set (optional)

Returns:



95
96
97
98
# File 'lib/hoodie/stash.rb', line 95

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.

Parameters:

  • key (Symbol, String) (defaults to: nil)

    (optional) representing the key to

Returns:

  • nothing.



67
68
69
70
# File 'lib/hoodie/stash.rb', line 67

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

#include?(key = nil) ⇒ TrueClass, FalseClass

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

Parameters:

  • key (Symbol, String) (defaults to: nil)

    a string or symbol representing the key

Returns:



114
115
116
117
# File 'lib/hoodie/stash.rb', line 114

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

#sizeFixnum

return the size of the store as an integer

Returns:

  • (Fixnum)


104
105
106
# File 'lib/hoodie/stash.rb', line 104

def size
  @store.size
end