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.



1909
1910
1911
1912
1913
1914
# File 'lib/syntax_tree.rb', line 1909

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



1907
1908
1909
# File 'lib/syntax_tree.rb', line 1907

def comments
  @comments
end

#keyObject (readonly)

untyped

the key of this pair



1898
1899
1900
# File 'lib/syntax_tree.rb', line 1898

def key
  @key
end

#locationObject (readonly)

Location

the location of this node



1904
1905
1906
# File 'lib/syntax_tree.rb', line 1904

def location
  @location
end

#valueObject (readonly)

untyped

the value of this pair



1901
1902
1903
# File 'lib/syntax_tree.rb', line 1901

def value
  @value
end

Instance Method Details

#child_nodesObject



1916
1917
1918
# File 'lib/syntax_tree.rb', line 1916

def child_nodes
  [key, value]
end

#format(q) ⇒ Object



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

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

#pretty_print(q) ⇒ Object



1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
# File 'lib/syntax_tree.rb', line 1928

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



1944
1945
1946
1947
1948
1949
1950
1951
1952
# File 'lib/syntax_tree.rb', line 1944

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