Class: Xf::Trace
- Inherits:
-
Object
- Object
- Xf::Trace
- Defined in:
- lib/xf/trace.rb
Overview
A more abstract version of a Scope in which the lead key is treated as if it could be anywhere in a hash tree. A Trace will dive until it finds all matching nodes.
Note that this can potentially be slow, but is also very difficult to emulate succinctly inline in vanilla Ruby.
Direct Known Subclasses
Instance Method Summary collapse
-
#get(&fn) ⇒ Proc[Hash] -
Gets a value from a Hash.
- #get_value(hash, &fn) ⇒ Object
-
#initialize(trace_path) ⇒ Xf::Trace
constructor
Creates a Scope.
-
#set(value = nil, &fn) ⇒ Proc[Hash] -
Sets a value in a Hash.
-
#set!(value = nil, &fn) ⇒ Object
Mutates a value in a Hash.
- #set_value(hash, value = nil, &fn) ⇒ Object
- #set_value!(hash, value = nil, &fn) ⇒ Object
Constructor Details
#initialize(trace_path) ⇒ Xf::Trace
Creates a Scope
19 20 21 |
# File 'lib/xf/trace.rb', line 19 def initialize(trace_path) @trace_path = trace_path end |
Instance Method Details
#get(&fn) ⇒ Proc[Hash] -
Gets a value from a Hash
31 32 33 |
# File 'lib/xf/trace.rb', line 31 def get(&fn) Proc.new { |target| get_value(target, &fn) } end |
#get_value(hash, &fn) ⇒ Object
35 36 37 38 39 40 41 42 43 |
# File 'lib/xf/trace.rb', line 35 def get_value(hash, &fn) retrieved_values = [] recursing_dive(hash) { |h, k, v| retrieved_values.push(block_given? ? fn[h, k, v] : v) } retrieved_values end |
#set(value = nil, &fn) ⇒ Proc[Hash] -
Sets a value in a Hash
56 57 58 |
# File 'lib/xf/trace.rb', line 56 def set(value = nil, &fn) Proc.new { |hash| set_value(hash, value, &fn) } end |
#set!(value = nil, &fn) ⇒ Object
Note:
This method does the same thing as ‘#set`, except that it mutates the target value instead of creating a clone first.
Mutates a value in a Hash
68 69 70 |
# File 'lib/xf/trace.rb', line 68 def set!(value = nil, &fn) Proc.new { |hash| set_value!(hash, value, &fn) } end |
#set_value(hash, value = nil, &fn) ⇒ Object
72 73 74 |
# File 'lib/xf/trace.rb', line 72 def set_value(hash, value = nil, &fn) set_value!(deep_clone(hash), value, &fn) end |
#set_value!(hash, value = nil, &fn) ⇒ Object
76 77 78 79 80 81 82 |
# File 'lib/xf/trace.rb', line 76 def set_value!(hash, value = nil, &fn) recursing_dive(hash) { |h, k, v| h[k] = block_given? ? yield(v) : value } hash end |