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.



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

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



1536
1537
1538
# File 'lib/syntax_tree/node.rb', line 1536

def comments
  @comments
end

#keyObject (readonly)

untyped

the key of this pair



1530
1531
1532
# File 'lib/syntax_tree/node.rb', line 1530

def key
  @key
end

#valueObject (readonly)

untyped

the value of this pair



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

def value
  @value
end

Instance Method Details

#===(other) ⇒ Object



1579
1580
1581
# File 'lib/syntax_tree/node.rb', line 1579

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

#accept(visitor) ⇒ Object



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

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

#child_nodesObject Also known as: deconstruct



1549
1550
1551
# File 'lib/syntax_tree/node.rb', line 1549

def child_nodes
  [key, value]
end

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



1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
# File 'lib/syntax_tree/node.rb', line 1553

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



1567
1568
1569
# File 'lib/syntax_tree/node.rb', line 1567

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

#format(q) ⇒ Object



1571
1572
1573
1574
1575
1576
1577
# File 'lib/syntax_tree/node.rb', line 1571

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