Class: SyntaxTree::Assoc

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

Overview

Assoc represents a key-value pair within a hash. It is a child node of either an AssocListFromArgs or a BareAssocHash.

{ key1: value1, key2: value2 }

In the above example, the would be two Assoc nodes.

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#construct_keys, #pretty_print, #to_json

Constructor Details

#initialize(key:, value:, location:) ⇒ Assoc

Returns a new instance of Assoc.



1492
1493
1494
1495
1496
1497
# File 'lib/syntax_tree/node.rb', line 1492

def initialize(key:, value:, location:)
  @key = key
  @value = value
  @location = location
  @comments = []
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



1490
1491
1492
# File 'lib/syntax_tree/node.rb', line 1490

def comments
  @comments
end

#keyObject (readonly)

untyped

the key of this pair



1484
1485
1486
# File 'lib/syntax_tree/node.rb', line 1484

def key
  @key
end

#valueObject (readonly)

untyped

the value of this pair



1487
1488
1489
# File 'lib/syntax_tree/node.rb', line 1487

def value
  @value
end

Instance Method Details

#===(other) ⇒ Object



1533
1534
1535
# File 'lib/syntax_tree/node.rb', line 1533

def ===(other)
  other.is_a?(Assoc) && key === other.key && value === other.value
end

#accept(visitor) ⇒ Object



1499
1500
1501
# File 'lib/syntax_tree/node.rb', line 1499

def accept(visitor)
  visitor.visit_assoc(self)
end

#child_nodesObject Also known as: deconstruct



1503
1504
1505
# File 'lib/syntax_tree/node.rb', line 1503

def child_nodes
  [key, value]
end

#copy(key: nil, value: nil, location: nil) ⇒ Object



1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
# File 'lib/syntax_tree/node.rb', line 1507

def copy(key: nil, value: nil, location: nil)
  node =
    Assoc.new(
      key: key || self.key,
      value: value || self.value,
      location: location || self.location
    )

  node.comments.concat(comments.map(&:copy))
  node
end

#deconstruct_keys(_keys) ⇒ Object



1521
1522
1523
# File 'lib/syntax_tree/node.rb', line 1521

def deconstruct_keys(_keys)
  { key: key, value: value, location: location, comments: comments }
end

#format(q) ⇒ Object



1525
1526
1527
1528
1529
1530
1531
# File 'lib/syntax_tree/node.rb', line 1525

def format(q)
  if value.is_a?(HashLiteral)
    format_contents(q)
  else
    q.group { format_contents(q) }
  end
end