Class: SyntaxTree::Assoc

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

Overview

Assoc represents a key-value pair within a hash. It is a child node of either an AssocListFromArgs or a BareAssocHash.

{ key1: value1, key2: value2 }

In the above example, the would be two AssocNew nodes.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, value:, location:, comments: []) ⇒ Assoc

Returns a new instance of Assoc.



1424
1425
1426
1427
1428
1429
# File 'lib/syntax_tree/node.rb', line 1424

def initialize(key:, value:, location:, comments: [])
  @key = key
  @value = value
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



1422
1423
1424
# File 'lib/syntax_tree/node.rb', line 1422

def comments
  @comments
end

#keyObject (readonly)

untyped

the key of this pair



1413
1414
1415
# File 'lib/syntax_tree/node.rb', line 1413

def key
  @key
end

#locationObject (readonly)

Location

the location of this node



1419
1420
1421
# File 'lib/syntax_tree/node.rb', line 1419

def location
  @location
end

#valueObject (readonly)

untyped

the value of this pair



1416
1417
1418
# File 'lib/syntax_tree/node.rb', line 1416

def value
  @value
end

Instance Method Details

#child_nodesObject Also known as: deconstruct



1431
1432
1433
# File 'lib/syntax_tree/node.rb', line 1431

def child_nodes
  [key, value]
end

#deconstruct_keys(keys) ⇒ Object



1437
1438
1439
# File 'lib/syntax_tree/node.rb', line 1437

def deconstruct_keys(keys)
  { key: key, value: value, location: location, comments: comments }
end

#format(q) ⇒ Object



1441
1442
1443
1444
1445
1446
1447
# File 'lib/syntax_tree/node.rb', line 1441

def format(q)
  if value&.is_a?(HashLiteral)
    format_contents(q)
  else
    q.group { format_contents(q) }
  end
end

#pretty_print(q) ⇒ Object



1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
# File 'lib/syntax_tree/node.rb', line 1449

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

    q.breakable
    q.pp(key)

    if value
      q.breakable
      q.pp(value)
    end

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

#to_json(*opts) ⇒ Object



1465
1466
1467
1468
1469
1470
1471
1472
1473
# File 'lib/syntax_tree/node.rb', line 1465

def to_json(*opts)
  {
    type: :assoc,
    key: key,
    value: value,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end