Class: JsonPath::Enumerable

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Dig
Defined in:
lib/jsonpath/enumerable.rb

Instance Method Summary collapse

Methods included from Dig

#dig, #dig_as_hash, #dig_one, #yield_if_diggable

Constructor Details

#initialize(path, object, mode, options = {}) ⇒ Enumerable

Returns a new instance of Enumerable.



8
9
10
11
12
13
# File 'lib/jsonpath/enumerable.rb', line 8

def initialize(path, object, mode, options = {})
  @path = path.path
  @object = object
  @mode = mode
  @options = options
end

Instance Method Details

#each(context = @object, key = nil, pos = 0, &blk) ⇒ Object



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
# File 'lib/jsonpath/enumerable.rb', line 15

def each(context = @object, key = nil, pos = 0, &blk)
  node = key ? dig_one(context, key) : context
  @_current_node = node
  return yield_value(blk, context, key) if pos == @path.size

  case expr = @path[pos]
  when '*', '..', '@'
    each(context, key, pos + 1, &blk)
  when '$'
    if node == @object
      each(context, key, pos + 1, &blk)
    else
      handle_wildcard(node, "['#{expr}']", context, key, pos, &blk)
    end
  when /^\[(.*)\]$/
    handle_wildcard(node, expr, context, key, pos, &blk)
  when /\(.*\)/
    keys = expr.gsub(/[()]/, '').split(',').map(&:strip)
    new_context = filter_context(context, keys)
    yield_value(blk, new_context, key)
  end

  if pos > 0 && @path[pos - 1] == '..' || (@path[pos - 1] == '*' && @path[pos] != '..')
    case node
    when Hash  then node.each { |k, _| each(node, k, pos, &blk) }
    when Array then node.each_with_index { |_, i| each(node, i, pos, &blk) }
    end
  end
end