Module: QAT::Utils::Hash

Defined in:
lib/qat/utils/hash.rb

Overview

This module gives helper methods for Hash

Class Method Summary collapse

Class Method Details

Returns values form a given path (keys) of a complex structure of data



13
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/qat/utils/hash.rb', line 13

def navigate_path(node, path, possible_leaf_nodes = [])

  node = node.dup.symbolize_keys if node.kind_of?(::Hash)

  if path.empty?
    possible_leaf_nodes << node
    return possible_leaf_nodes
  end

  path      = path.dup
  path_head = path.shift
  regex     = '.*\[(\*|-?\d+)\]'

  obj_index = nil
  match     = path_head.to_s.match(regex)
  if match
    index     = match.begin(1)
    obj_index = match[1]
    path_head = path_head.slice(0, index - 1).to_sym
  end

  if !node || (!node.kind_of?(Array) && !node.keys.map(&:to_sym).include?(path_head.to_sym))
    possible_leaf_nodes << :field_not_found
    return possible_leaf_nodes
  end

  new_node = nil
  if node.kind_of?(Array) && obj_index #index is prefixed
    if obj_index.eql? '*'
      node.each do |item|
        navigate_path(item, path, possible_leaf_nodes)
      end
      possible_leaf_nodes
    else
      new_node = node[obj_index.to_i]
    end

  else
    new_node = node[path_head.to_sym]
  end


  if new_node.kind_of?(Array) && obj_index #index is suffixed
    if obj_index.eql? '*'
      new_node.each do |item|
        navigate_path(item, path, possible_leaf_nodes)
      end
      possible_leaf_nodes
    else
      new_node = new_node[obj_index.to_i]
      navigate_path(new_node, path, possible_leaf_nodes)
    end
  else
    navigate_path(new_node, path, possible_leaf_nodes)
  end
end