Class: SyntaxTree::HashLiteral

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

Overview

HashLiteral represents a hash literal.

{ key => value }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lbrace:, assocs:, location:, comments: []) ⇒ HashLiteral

Returns a new instance of HashLiteral.



5524
5525
5526
5527
5528
5529
# File 'lib/syntax_tree/node.rb', line 5524

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

Instance Attribute Details

#assocsObject (readonly)

Array[ AssocNew | AssocSplat ]

the optional contents of the hash



5516
5517
5518
# File 'lib/syntax_tree/node.rb', line 5516

def assocs
  @assocs
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



5522
5523
5524
# File 'lib/syntax_tree/node.rb', line 5522

def comments
  @comments
end

#lbraceObject (readonly)

LBrace

the left brace that opens this hash



5513
5514
5515
# File 'lib/syntax_tree/node.rb', line 5513

def lbrace
  @lbrace
end

#locationObject (readonly)

Location

the location of this node



5519
5520
5521
# File 'lib/syntax_tree/node.rb', line 5519

def location
  @location
end

Instance Method Details

#child_nodesObject Also known as: deconstruct



5531
5532
5533
# File 'lib/syntax_tree/node.rb', line 5531

def child_nodes
  [lbrace] + assocs
end

#deconstruct_keys(keys) ⇒ Object



5537
5538
5539
# File 'lib/syntax_tree/node.rb', line 5537

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

#format(q) ⇒ Object



5541
5542
5543
5544
5545
5546
5547
# File 'lib/syntax_tree/node.rb', line 5541

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



5549
5550
5551
# File 'lib/syntax_tree/node.rb', line 5549

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

#pretty_print(q) ⇒ Object



5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
# File 'lib/syntax_tree/node.rb', line 5553

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("hash")

    if assocs.any?
      q.breakable
      q.group(2, "(", ")") { q.seplist(assocs) { |assoc| q.pp(assoc) } }
    end

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



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

def to_json(*opts)
  { type: :hash, assocs: assocs, loc: location, cmts: comments }.to_json(
    *opts
  )
end