Class: Kitchen::LazyHash
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- Kitchen::LazyHash
- Defined in:
- lib/kitchen/lazy_hash.rb
Overview
A modifed Hash object that may contain callables as a value which must be executed in the context of another object. This allows for delayed evaluation of a hash value while still looking and largely feeling like a normal Ruby Hash.
Instance Method Summary collapse
-
#[](key) ⇒ Object?
Retrieves the rendered value object corresponding to the key object.
-
#fetch(key, default = :__undefined__, &block) ⇒ Object?
Returns a rendered value from the hash for the given key.
-
#initialize(obj, context) ⇒ LazyHash
constructor
Creates a new LazyHash using a Hash-like object to populate itself and an object that can be used as context in value-callable blocks.
-
#to_hash ⇒ Hash
Returns a new Hash with all keys and rendered values of the LazyHash.
Constructor Details
#initialize(obj, context) ⇒ LazyHash
Creates a new LazyHash using a Hash-like object to populate itself and an object that can be used as context in value-callable blocks. The context object can be used to compute values for keys at the time of fetching the value.
64 65 66 67 |
# File 'lib/kitchen/lazy_hash.rb', line 64 def initialize(obj, context) @context = context super(obj) end |
Instance Method Details
#[](key) ⇒ Object?
Retrieves the rendered value object corresponding to the key object. If not found, returns the default value.
75 76 77 |
# File 'lib/kitchen/lazy_hash.rb', line 75 def [](key) proc_or_val(__getobj__[key]) end |
#fetch(key, default = :__undefined__, &block) ⇒ Object?
Returns a rendered value from the hash for the given key. If the key can't be found, there are several options: With no other arguments, it will raise an KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.
90 91 92 93 94 95 96 97 |
# File 'lib/kitchen/lazy_hash.rb', line 90 def fetch(key, default = :__undefined__, &block) case default when :__undefined__ proc_or_val(__getobj__.fetch(key, &block)) else proc_or_val(__getobj__.fetch(key, default, &block)) end end |