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.



2376
2377
2378
2379
2380
2381
# File 'lib/syntax_tree/node.rb', line 2376

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_closeObject (readonly)

String

the string that closes the block



2371
2372
2373
# File 'lib/syntax_tree/node.rb', line 2371

def block_close
  @block_close
end

#block_openObject (readonly)

LBrace | Keyword

the node that opens the block



2368
2369
2370
# File 'lib/syntax_tree/node.rb', line 2368

def block_open
  @block_open
end

#nodeObject (readonly)

BraceBlock | DoBlock

the block node to be formatted



2365
2366
2367
# File 'lib/syntax_tree/node.rb', line 2365

def node
  @node
end

#statementsObject (readonly)

BodyStmt | Statements

the statements inside the block



2374
2375
2376
# File 'lib/syntax_tree/node.rb', line 2374

def statements
  @statements
end

Instance Method Details

#format(q) ⇒ Object



2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
# File 'lib/syntax_tree/node.rb', line 2383

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 do
      format_flat(q, flat_opening, flat_closing)
    end
  end
end