Class: Dagger::Default
- Inherits:
-
Object
- Object
- Dagger::Default
- Defined in:
- lib/dagger/default.rb
Overview
Default value generator for a dictionary
Instance Attribute Summary collapse
-
#cached ⇒ Object
writeonly
Sets the attribute cached.
-
#default_proc ⇒ Object
readonly
Returns the value of attribute default_proc.
Instance Method Summary collapse
-
#cached? ⇒ Boolean
Verify state of caching of future values.
-
#generate(tree, key) ⇒ Object
Generate a default value for a
key, possibly caching the result in thetree. -
#initialize(dictionary, cached: false, rule_prefix: '_default') ⇒ Default
constructor
Initialize a default value generator for a
dictionary.
Constructor Details
#initialize(dictionary, cached: false, rule_prefix: '_default') ⇒ Default
Initialize a default value generator for a dictionary
:call-seq:
new(dictionary) => Dagger::Default
new(*, cached: false)
new(*, rule_prefix: '_default')
14 15 16 17 18 19 20 |
# File 'lib/dagger/default.rb', line 14 def initialize(dictionary, cached: false, rule_prefix: '_default') @dictionary = dictionary @cached = cached @rule_prefix = KeyTree::Path[rule_prefix] @default_proc = ->(tree, key) { generate(tree, key) } @locks = Set[] end |
Instance Attribute Details
#cached=(value) ⇒ Object (writeonly)
Sets the attribute cached
31 32 33 |
# File 'lib/dagger/default.rb', line 31 def cached=(value) @cached = value end |
#default_proc ⇒ Object (readonly)
Returns the value of attribute default_proc.
22 23 24 |
# File 'lib/dagger/default.rb', line 22 def default_proc @default_proc end |
Instance Method Details
#cached? ⇒ Boolean
Verify state of caching of future values
:call-seq:
cached? => bool
28 29 30 |
# File 'lib/dagger/default.rb', line 28 def cached? !(!@cached) end |
#generate(tree, key) ⇒ Object
Generate a default value for a key, possibly caching the result in the tree. Raises a KeyError f the default value cannot be generated.
:call-seq:
generate(tree, key) => value || KeyError
39 40 41 42 43 44 45 46 47 |
# File 'lib/dagger/default.rb', line 39 def generate(tree, key) key = KeyTree::Path[key] unless key.is_a? KeyTree::Path raise %(deadlock detected: "#{key}") unless @locks.add?(key) return result = process(key) unless cached? tree[key] = result unless result.nil? ensure @locks.delete(key) end |