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.



6283
6284
6285
6286
6287
6288
# File 'lib/syntax_tree.rb', line 6283

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



6275
6276
6277
# File 'lib/syntax_tree.rb', line 6275

def assocs
  @assocs
end

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



6281
6282
6283
# File 'lib/syntax_tree.rb', line 6281

def comments
  @comments
end

#lbraceObject (readonly)

LBrace

the left brace that opens this hash



6272
6273
6274
# File 'lib/syntax_tree.rb', line 6272

def lbrace
  @lbrace
end

#locationObject (readonly)

Location

the location of this node



6278
6279
6280
# File 'lib/syntax_tree.rb', line 6278

def location
  @location
end

Instance Method Details

#child_nodesObject



6290
6291
6292
# File 'lib/syntax_tree.rb', line 6290

def child_nodes
  [lbrace] + assocs
end

#format(q) ⇒ Object



6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
# File 'lib/syntax_tree.rb', line 6294

def format(q)
  contents = -> do
    q.format(lbrace)

    if assocs.empty?
      q.breakable("")
    else
      q.indent do
        q.breakable
        q.format(HashFormatter.for(self))
      end
      q.breakable
    end

    q.text("}")
  end

  q.parent.is_a?(Assoc) ? contents.call : q.group(&contents)
end

#pretty_print(q) ⇒ Object



6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
# File 'lib/syntax_tree.rb', line 6314

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



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

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