lib/rubocop/cop/layout/multiline_block_layout.rb in rubocop-0.74.0 vs lib/rubocop/cop/layout/multiline_block_layout.rb in rubocop-0.75.0
- old
+ new
@@ -3,11 +3,13 @@
module RuboCop
module Cop
module Layout
# This cop checks whether the multiline do end blocks have a newline
# after the start of the block. Additionally, it checks whether the block
- # arguments, if any, are on the same line as the start of the block.
+ # arguments, if any, are on the same line as the start of the
+ # block. Putting block arguments on separate lines, because the whole
+ # line would otherwise be too long, is accepted.
#
# @example
# # bad
# blah do |i| foo(i)
# bar(i)
@@ -33,22 +35,35 @@
# # good
# blah { |i|
# foo(i)
# bar(i)
# }
+ #
+ # # good
+ # blah { |
+ # long_list,
+ # of_parameters,
+ # that_would_not,
+ # fit_on_one_line
+ # |
+ # foo(i)
+ # bar(i)
+ # }
class MultilineBlockLayout < Cop
include RangeHelp
MSG = 'Block body expression is on the same line as ' \
'the block start.'
ARG_MSG = 'Block argument expression is not on the same line as the ' \
'block start.'
+ PIPE_SIZE = '|'.length
def on_block(node)
return if node.single_line?
- unless args_on_beginning_line?(node)
+ unless args_on_beginning_line?(node) ||
+ line_break_necessary_in_args?(node)
add_offense_for_expression(node, node.arguments, ARG_MSG)
end
return unless node.body && node.loc.begin.line == node.body.first_line
@@ -75,9 +90,16 @@
private
def args_on_beginning_line?(node)
!node.arguments? ||
node.loc.begin.line == node.arguments.loc.last_line
+ end
+
+ def line_break_necessary_in_args?(node)
+ needed_length = node.source_range.column +
+ node.source.lines.first.length +
+ block_arg_string(node.arguments).length + PIPE_SIZE
+ needed_length > max_line_length
end
def add_offense_for_expression(node, expr, msg)
expression = expr.source_range
range = range_between(expression.begin_pos, expression.end_pos)