Class: HashSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_selector.rb,
lib/hash_selector/version.rb

Overview

Selects a value from a complex or deeply nested hash structure with default values.

Example

HashSelector.new[:bar].find_in(foo: { bar: { baz: 42 } } ) # => 42

HashSelector.new[:bar].find_in(foo: nil) { 42 } # => 42

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

Returns a new selector that selects the specified key from result of the current selector.



17
18
19
20
21
22
23
24
25
# File 'lib/hash_selector.rb', line 17

def [](key)
  HashSelector.new steps + [ ->(subject) {
                               begin
                                 subject.fetch(key)
                               rescue IndexError
                                 raise KeyError
                               end
                             } ]
end

#find(&blk) ⇒ Object Also known as: detect

Returns a new selector that selects an entry from the result of the current selector using a predicate block.



29
30
31
32
33
34
35
36
37
38
# File 'lib/hash_selector.rb', line 29

def find(&blk)
  HashSelector.new steps + [ ->(subject) {
                                 needle = subject.find(->(){ MISSING }, &blk)
                                 if MISSING == needle
                                   fail KeyError
                                 else
                                   needle
                                 end
                             } ]
end

#find_in(hay_stack) ⇒ Object

Returns the value from a hash at the location specified by this selector.



42
43
44
45
46
47
48
49
50
51
# File 'lib/hash_selector.rb', line 42

def find_in(hay_stack)
  steps.reduce(hay_stack) { |search_area, step| step.call(search_area) }

rescue KeyError
  if block_given?
    yield hay_stack
  else
    raise
  end
end