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, #end_char, #pretty_print, #start_char, #to_json, #to_mermaid

Constructor Details

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

Returns a new instance of Assoc.



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

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



1501
1502
1503
# File 'lib/syntax_tree/node.rb', line 1501

def comments
  @comments
end

#keyObject (readonly)

Node

the key of this pair



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

def key
  @key
end

#valueObject (readonly)

nil | Node

the value of this pair



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

def value
  @value
end

Instance Method Details

#===(other) ⇒ Object



1544
1545
1546
# File 'lib/syntax_tree/node.rb', line 1544

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

#accept(visitor) ⇒ Object



1510
1511
1512
# File 'lib/syntax_tree/node.rb', line 1510

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

#child_nodesObject Also known as: deconstruct



1514
1515
1516
# File 'lib/syntax_tree/node.rb', line 1514

def child_nodes
  [key, value]
end

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



1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/syntax_tree/node.rb', line 1518

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



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

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

#format(q) ⇒ Object



1536
1537
1538
1539
1540
1541
1542
# File 'lib/syntax_tree/node.rb', line 1536

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