Class: Rjq::AST::Index

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, index, optional: false) ⇒ Index

Returns a new instance of Index.



431
432
433
434
435
# File 'lib/rjq/ast.rb', line 431

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

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



429
430
431
# File 'lib/rjq/ast.rb', line 429

def base
  @base
end

#indexObject (readonly)

Returns the value of attribute index.



429
430
431
# File 'lib/rjq/ast.rb', line 429

def index
  @index
end

Instance Method Details

#eval(input, context) ⇒ Object



437
438
439
440
441
442
443
# File 'lib/rjq/ast.rb', line 437

def eval(input, context)
  @base.eval(input, context).flat_map do |value|
    @index.eval(input, context).map { |idx| read(value, idx) }
  rescue Rjq::RuntimeError
    @optional ? [] : raise
  end
end

#invalid_path_message(result, input, context) ⇒ Object



453
454
455
456
457
458
459
# File 'lib/rjq/ast.rb', line 453

def invalid_path_message(result, input, context)
  index = @index.eval(input, context).first
  "Invalid path expression near attempt to access element #{JSON::Dumper.dump(index,
                                                                              indent: nil)} of #{JSON::Dumper.dump(
                                                                                result, indent: nil
                                                                              )}"
end

#paths(input, context) ⇒ Object



445
446
447
448
449
450
451
# File 'lib/rjq/ast.rb', line 445

def paths(input, context)
  indices = @index.eval(input, context)
  @base.paths(input, context).flat_map do |path|
    value = Path.get(input, path)
    indices.map { |index| path + [path_index(value, index)] }
  end
end