Class: ChefStash::Cache

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

Overview

Chef Key/value stash cache hash objects store.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Cache

Initializes a new Chef Key/value stash cache hash objects store.



62
63
64
65
# File 'lib/chef_stash.rb', line 62

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

Instance Attribute Details

#:store(: store) ⇒ ChefStash (readonly)



58
# File 'lib/chef_stash.rb', line 58

attr_reader :store

#storeHash (readonly)



58
59
60
# File 'lib/chef_stash.rb', line 58

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



76
77
78
79
80
# File 'lib/chef_stash.rb', line 76

def [](key = nil)
  key ||= ChefStash.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



90
91
92
93
# File 'lib/chef_stash.rb', line 90

def cache(key = nil, &code)
  key ||= ChefStash.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.



113
114
115
# File 'lib/chef_stash.rb', line 113

def clear!(key = nil)
  key.nil? ? @store.clear : @store.delete(key)
end

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

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



101
102
103
104
# File 'lib/chef_stash.rb', line 101

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

#sizeFixnum

return the size of the store as an integer



121
122
123
# File 'lib/chef_stash.rb', line 121

def size
  @store.size
end