Class: Rjq::AST::Iterate

Inherits:
Node
  • Object
show all
Defined in:
lib/rjq/ast.rb

Instance Attribute Summary collapse

Attributes inherited from Node

#source_span

Instance Method Summary collapse

Methods inherited from Node

#assign_value, #take, #with_source_span

Constructor Details

#initialize(base, optional: false) ⇒ Iterate

Returns a new instance of Iterate.



565
566
567
568
# File 'lib/rjq/ast.rb', line 565

def initialize(base, optional: false)
  @base = base
  @optional = optional
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



563
564
565
# File 'lib/rjq/ast.rb', line 563

def base
  @base
end

Instance Method Details

#eval(input, context) ⇒ Object



570
571
572
573
574
575
576
# File 'lib/rjq/ast.rb', line 570

def eval(input, context)
  @base.eval(input, context).flat_map do |value|
    iterate(value)
  rescue Rjq::RuntimeError
    @optional ? [] : raise
  end
end

#invalid_path_message(result, _input, _context) ⇒ Object



595
596
597
# File 'lib/rjq/ast.rb', line 595

def invalid_path_message(result, _input, _context)
  "Invalid path expression near attempt to iterate through #{JSON::Dumper.dump(result, indent: nil)}"
end

#paths(input, context) ⇒ Object



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/rjq/ast.rb', line 578

def paths(input, context)
  @base.eval(input, context).flat_map do |value|
    keys =
      case value
      when Array
        (0...value.length).to_a
      when Hash
        value.keys
      else
        raise TypeError, "cannot iterate over #{Value.type_of(value)}"
      end
    @base.paths(input, context).flat_map { |path| keys.map { |key| path + [key] } }
  end
rescue InvalidPathError => e
  raise InvalidPathError.new(invalid_path_message(e.result, input, context), e.result)
end