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.



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

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



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

def assocs
  @assocs
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



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

def comments
  @comments
end

#lbraceObject (readonly)

LBrace

the left brace that opens this hash



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

def lbrace
  @lbrace
end

Instance Method Details

#===(other) ⇒ Object



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

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

#accept(visitor) ⇒ Object



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

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

#child_nodesObject Also known as: deconstruct



5590
5591
5592
# File 'lib/syntax_tree/node.rb', line 5590

def child_nodes
  [lbrace] + assocs
end

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



5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
# File 'lib/syntax_tree/node.rb', line 5594

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



5608
5609
5610
# File 'lib/syntax_tree/node.rb', line 5608

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

#format(q) ⇒ Object



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

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



5625
5626
5627
# File 'lib/syntax_tree/node.rb', line 5625

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