Class: SyntaxTree::ARef

Inherits:
Node
  • Object
show all
Defined in:
lib/syntax_tree/node.rb

Overview

ARef represents when you’re pulling a value out of a collection at a specific index. Put another way, it’s any time you’re calling the method #[].

collection[index]

The nodes usually contains two children, the collection and the index. In some cases, you don’t necessarily have the second child node, because you can call procs with a pretty esoteric syntax. In the following example, you wouldn’t have a second child node:

collection[]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection:, index:, location:, comments: []) ⇒ ARef

Returns a new instance of ARef.



493
494
495
496
497
498
# File 'lib/syntax_tree/node.rb', line 493

def initialize(collection:, index:, location:, comments: [])
  @collection = collection
  @index = index
  @location = location
  @comments = comments
end

Instance Attribute Details

#collectionObject (readonly)

untyped

the value being indexed



482
483
484
# File 'lib/syntax_tree/node.rb', line 482

def collection
  @collection
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



491
492
493
# File 'lib/syntax_tree/node.rb', line 491

def comments
  @comments
end

#indexObject (readonly)

nil | Args

the value being passed within the brackets



485
486
487
# File 'lib/syntax_tree/node.rb', line 485

def index
  @index
end

#locationObject (readonly)

Location

the location of this node



488
489
490
# File 'lib/syntax_tree/node.rb', line 488

def location
  @location
end

Instance Method Details

#child_nodesObject Also known as: deconstruct



500
501
502
# File 'lib/syntax_tree/node.rb', line 500

def child_nodes
  [collection, index]
end

#deconstruct_keys(keys) ⇒ Object



506
507
508
509
510
511
512
513
# File 'lib/syntax_tree/node.rb', line 506

def deconstruct_keys(keys)
  {
    collection: collection,
    index: index,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/syntax_tree/node.rb', line 515

def format(q)
  q.group do
    q.format(collection)
    q.text("[")

    if index
      q.indent do
        q.breakable("")
        q.format(index)
      end
      q.breakable("")
    end

    q.text("]")
  end
end

#pretty_print(q) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/syntax_tree/node.rb', line 532

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("aref")

    q.breakable
    q.pp(collection)

    q.breakable
    q.pp(index)

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



546
547
548
549
550
551
552
553
554
# File 'lib/syntax_tree/node.rb', line 546

def to_json(*opts)
  {
    type: :aref,
    collection: collection,
    index: index,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end