Class: SyntaxTree::HashLiteral

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

Overview

HashLiteral represents a hash literal.

{ key => value }

Defined Under Namespace

Classes: EmptyWithCommentsFormatter

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(lbrace:, assocs:, location:) ⇒ HashLiteral

Returns a new instance of HashLiteral.



5574
5575
5576
5577
5578
5579
# File 'lib/syntax_tree/node.rb', line 5574

def initialize(lbrace:, assocs:, location:)
  @lbrace = lbrace
  @assocs = assocs
  @location = location
  @comments = []
end

Instance Attribute Details

#assocsObject (readonly)

Array[ Assoc | AssocSplat ]

the optional contents of the hash



5569
5570
5571
# File 'lib/syntax_tree/node.rb', line 5569

def assocs
  @assocs
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



5572
5573
5574
# File 'lib/syntax_tree/node.rb', line 5572

def comments
  @comments
end

#lbraceObject (readonly)

LBrace

the left brace that opens this hash



5566
5567
5568
# File 'lib/syntax_tree/node.rb', line 5566

def lbrace
  @lbrace
end

Instance Method Details

#===(other) ⇒ Object



5615
5616
5617
5618
# File 'lib/syntax_tree/node.rb', line 5615

def ===(other)
  other.is_a?(HashLiteral) && lbrace === other.lbrace &&
    ArrayMatch.call(assocs, other.assocs)
end

#accept(visitor) ⇒ Object



5581
5582
5583
# File 'lib/syntax_tree/node.rb', line 5581

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

#child_nodesObject Also known as: deconstruct



5585
5586
5587
# File 'lib/syntax_tree/node.rb', line 5585

def child_nodes
  [lbrace] + assocs
end

#copy(lbrace: nil, assocs: nil, location: nil) ⇒ Object



5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
# File 'lib/syntax_tree/node.rb', line 5589

def copy(lbrace: nil, assocs: nil, location: nil)
  node =
    HashLiteral.new(
      lbrace: lbrace || self.lbrace,
      assocs: assocs || self.assocs,
      location: location || self.location
    )

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

#deconstruct_keys(_keys) ⇒ Object



5603
5604
5605
# File 'lib/syntax_tree/node.rb', line 5603

def deconstruct_keys(_keys)
  { lbrace: lbrace, assocs: assocs, location: location, comments: comments }
end

#format(q) ⇒ Object



5607
5608
5609
5610
5611
5612
5613
# File 'lib/syntax_tree/node.rb', line 5607

def format(q)
  if q.parent.is_a?(Assoc)
    format_contents(q)
  else
    q.group { format_contents(q) }
  end
end

#format_key(q, key) ⇒ Object



5620
5621
5622
# File 'lib/syntax_tree/node.rb', line 5620

def format_key(q, key)
  (@key_formatter ||= HashKeyFormatter.for(self)).format_key(q, key)
end