class RuboCop::Cop::Layout::SingleLineBlockChain

Checks if method calls are chained onto single line blocks. It considers that a line break before the dot improves the readability of the code.

@example

# bad
example.select { |item| item.cond? }.join('-')

# good
example.select { |item| item.cond? }
       .join('-')

# good (not a concern for this cop)
example.select do |item|
  item.cond?
end.join('-')

Constants

MSG

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/layout/single_line_block_chain.rb, line 28
def on_send(node)
  range = offending_range(node)
  add_offense(range) { |corrector| corrector.insert_before(range, "\n") } if range
end

Private Instance Methods

call_method_after_block?(node, dot_range, closing_block_delimiter_line_num) click to toggle source
# File lib/rubocop/cop/layout/single_line_block_chain.rb, line 51
def call_method_after_block?(node, dot_range, closing_block_delimiter_line_num)
  return false if dot_range.line > closing_block_delimiter_line_num

  dot_range.column < selector_range(node).column
end
offending_range(node) click to toggle source
# File lib/rubocop/cop/layout/single_line_block_chain.rb, line 35
def offending_range(node)
  receiver = node.receiver
  return unless receiver&.block_type?

  receiver_location = receiver.loc
  closing_block_delimiter_line_num = receiver_location.end.line
  return if receiver_location.begin.line < closing_block_delimiter_line_num

  node_location = node.loc
  dot_range = node_location.dot
  return unless dot_range
  return unless call_method_after_block?(node, dot_range, closing_block_delimiter_line_num)

  range_between(dot_range.begin_pos, selector_range(node).end_pos)
end
selector_range(node) click to toggle source
# File lib/rubocop/cop/layout/single_line_block_chain.rb, line 57
def selector_range(node)
  # l.(1) has no selector, so we use the opening parenthesis instead
  node.loc.selector || node.loc.begin
end