Class: Xf::Trace

Inherits:
Object
  • Object
show all
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.

Author:

  • baweaver

Since:

  • 0.1.0

Direct Known Subclasses

TraceKeyValue, TraceValue

Instance Method Summary collapse

Constructor Details

#initialize(trace_path) ⇒ Xf::Trace

Creates a Scope

Parameters:

  • trace_path (Any)

    What node to try and locate

Since:

  • 0.1.0



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

Parameters:

  • &fn (Proc)

    Block to yield the hash, key, and value from any matching element into. Used to transform returned values upon retrieval

Returns:

  • (Proc[Hash] -)

    Array] Array containing matching values, optionally transformed

Since:

  • 0.1.0



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

Since:

  • 0.1.0



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

Parameters:

  • value (defaults to: nil)

    nil [Any]

    Value to set at the target

  • &fn (Proc)

    Block to yield target value to. Returned value will be set as the new value at the target.

Returns:

  • (Proc[Hash] -)

    Hash] New Hash with transformation applied

Since:

  • 0.1.0



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

See Also:

Since:

  • 0.1.0



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

Since:

  • 0.1.0



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

Since:

  • 0.1.0



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