Class: SyntaxTree::BlockFormatter

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

Overview

Responsible for formatting either a BraceBlock or a DoBlock.

Defined Under Namespace

Classes: BlockOpenFormatter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node, block_open, block_close, statements) ⇒ BlockFormatter

Returns a new instance of BlockFormatter.



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

def initialize(node, block_open, block_close, statements)
  @node = node
  @block_open = block_open
  @block_close = block_close
  @statements = statements
end

Instance Attribute Details

#block_close ⇒ Object (readonly)

[String] the string that closes the block



1939
1940
1941
# File 'lib/syntax_tree/node.rb', line 1939

def block_close
  @block_close
end

#block_open ⇒ Object (readonly)

[LBrace | Keyword] the node that opens the block



1936
1937
1938
# File 'lib/syntax_tree/node.rb', line 1936

def block_open
  @block_open
end

#node ⇒ Object (readonly)

[BraceBlock | DoBlock] the block node to be formatted



1933
1934
1935
# File 'lib/syntax_tree/node.rb', line 1933

def node
  @node
end

#statements ⇒ Object (readonly)

[BodyStmt | Statements] the statements inside the block



1942
1943
1944
# File 'lib/syntax_tree/node.rb', line 1942

def statements
  @statements
end

Instance Method Details

#format(q) ⇒ Object



1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
# File 'lib/syntax_tree/node.rb', line 1951

def format(q)
  # If this is nested anywhere inside of a Command or CommandCall node, then
  # we can't change which operators we're using for the bounds of the block.
  break_opening, break_closing, flat_opening, flat_closing =
    if unchangeable_bounds?(q)
      [block_open.value, block_close, block_open.value, block_close]
    elsif forced_do_end_bounds?(q)
      %w[do end do end]
    elsif forced_brace_bounds?(q)
      %w[{ } { }]
    else
      %w[do end { }]
    end

  # If the receiver of this block a Command or CommandCall node, then there
  # are no parentheses around the arguments to that command, so we need to
  # break the block.
  receiver = q.parent.call
  if receiver.is_a?(Command) || receiver.is_a?(CommandCall)
    q.break_parent
    format_break(q, break_opening, break_closing)
    return
  end

  q.group do
    q
      .if_break { format_break(q, break_opening, break_closing) }
      .if_flat { format_flat(q, flat_opening, flat_closing) }
  end
end