Class: SyntaxTree::HashLiteral

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree.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.



6320
6321
6322
6323
6324
6325
# File 'lib/syntax_tree.rb', line 6320

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



6312
6313
6314
# File 'lib/syntax_tree.rb', line 6312

def assocs
  @assocs
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



6318
6319
6320
# File 'lib/syntax_tree.rb', line 6318

def comments
  @comments
end

#lbraceObject (readonly)

LBrace

the left brace that opens this hash



6309
6310
6311
# File 'lib/syntax_tree.rb', line 6309

def lbrace
  @lbrace
end

#locationObject (readonly)

Location

the location of this node



6315
6316
6317
# File 'lib/syntax_tree.rb', line 6315

def location
  @location
end

Instance Method Details

#child_nodesObject



6327
6328
6329
# File 'lib/syntax_tree.rb', line 6327

def child_nodes
  [lbrace] + assocs
end

#format(q) ⇒ Object



6331
6332
6333
6334
6335
6336
6337
# File 'lib/syntax_tree.rb', line 6331

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



6339
6340
6341
# File 'lib/syntax_tree.rb', line 6339

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

#pretty_print(q) ⇒ Object



6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
# File 'lib/syntax_tree.rb', line 6343

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



6356
6357
6358
6359
6360
# File 'lib/syntax_tree.rb', line 6356

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