Class: SyntaxTree::Assoc

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



1887
1888
1889
1890
1891
1892
# File 'lib/syntax_tree.rb', line 1887

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



1885
1886
1887
# File 'lib/syntax_tree.rb', line 1885

def comments
  @comments
end

#keyObject (readonly)

untyped

the key of this pair



1876
1877
1878
# File 'lib/syntax_tree.rb', line 1876

def key
  @key
end

#locationObject (readonly)

Location

the location of this node



1882
1883
1884
# File 'lib/syntax_tree.rb', line 1882

def location
  @location
end

#valueObject (readonly)

untyped

the value of this pair



1879
1880
1881
# File 'lib/syntax_tree.rb', line 1879

def value
  @value
end

Instance Method Details

#child_nodesObject



1894
1895
1896
# File 'lib/syntax_tree.rb', line 1894

def child_nodes
  [key, value]
end

#format(q) ⇒ Object



1898
1899
1900
1901
1902
1903
1904
# File 'lib/syntax_tree.rb', line 1898

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

#pretty_print(q) ⇒ Object



1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
# File 'lib/syntax_tree.rb', line 1906

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

    q.breakable
    q.pp(key)

    q.breakable
    q.pp(value)

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

#to_json(*opts) ⇒ Object



1920
1921
1922
1923
1924
1925
1926
1927
1928
# File 'lib/syntax_tree.rb', line 1920

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