Skip to content

Commit

Permalink
[Fix rubocop#12226] Fix false positives for `Layout/MultilineMethodCa…
Browse files Browse the repository at this point in the history
…llIndentation`

Fixes rubocop#12226.

This PR fixes false positives for `Layout/MultilineMethodCallIndentation`
when aligning methods in multiline block chain.
  • Loading branch information
koic authored and bbatsov committed Sep 30, 2023
1 parent 08f475d commit 5f17749
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12226](https://github.com/rubocop/rubocop/issues/12226): Fix false positives for `Layout/MultilineMethodCallIndentation` when aligning methods in multiline block chain. ([@koic][])
11 changes: 11 additions & 0 deletions lib/rubocop/cop/layout/multiline_method_call_indentation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ def semantic_alignment_node(node)
dot_right_above = get_dot_right_above(node)
return dot_right_above if dot_right_above

if (multiline_block_chain_node = find_multiline_block_chain_node(node))
return multiline_block_chain_node
end

node = first_call_has_a_dot(node)
return if node.loc.dot.line != node.first_line

Expand All @@ -219,6 +223,13 @@ def get_dot_right_above(node)
end
end

def find_multiline_block_chain_node(node)
return unless (block_node = node.each_descendant(:block, :numblock).first)
return unless block_node.multiline? && block_node.parent.call_type?

block_node.parent
end

def first_call_has_a_dot(node)
# descend to root of method chain
node = node.receiver while node.receiver
Expand Down
40 changes: 40 additions & 0 deletions spec/rubocop/cop/layout/multiline_method_call_indentation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,46 @@ def a
RUBY
end

it 'registers an offense and corrects misaligned methods in multiline block chain' do
expect_offense(<<~RUBY)
do_something.foo do
end.bar
.baz
^^^^ Align `.baz` with `.bar` on line 2.
RUBY

expect_correction(<<~RUBY)
do_something.foo do
end.bar
.baz
RUBY
end

it 'accepts aligned methods in multiline block chain' do
expect_no_offenses(<<~RUBY)
do_something.foo do
end.bar
.baz
RUBY
end

it 'accepts aligned methods in multiline numbered block chain' do
expect_no_offenses(<<~RUBY)
do_something.foo do
bar(_1)
end.baz
.qux
RUBY
end

it 'accepts aligned methods in multiline block chain with safe navigation operator' do
expect_no_offenses(<<~RUBY)
do_something.foo do
end&.bar
&.baz
RUBY
end

it 'registers an offense and corrects misaligned methods in local variable assignment' do
expect_offense(<<~RUBY)
a = b.c.
Expand Down

0 comments on commit 5f17749

Please sign in to comment.