Class: HashDigger::Digger

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_digger.rb

Class Method Summary collapse

Class Method Details

.dig(data:, path:, strict: true, default: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/hash_digger.rb', line 14

def dig(data:, path:, strict: true, default: nil)
  if data.respond_to?(:keys)
    data = data.deep_symbolize_keys
  end

  # form the path of non enumerable diggable groups
  path = path(path)

  until path.empty? do
    # *.* stands for "flatten the top level arrays until there's one * left
    # which means iterate the fetcher with the following path over the result of the flattening"
    while path.fetch(0) === '*' && path&.fetch(1, nil) === '*' do
      data = data.flatten(1)
      path.shift
    end

    # if the path ends with a "*" and that's it
    return (block_given? ? yield(data) : data) if path.length === 1 && path.fetch(0) === '*'

    subpath = path.shift

    if subpath === '*'
      subpath = path.shift
      data = data&.collect {|node| fetch(data: node, path: subpath, strict: strict, default: default) }
    else
      data = fetch(data: data, path: subpath, strict: strict, default: default)
    end
  end

  # return data or apply the custom block handler to the whole result
  return (block_given? ? yield(data) : data)
end