Skip to content

Commit

Permalink
[Fix rubocop#9928] Fix a false auto-correct for Layout/EndAlignment
Browse files Browse the repository at this point in the history
Fixes rubocop#9928.

This PR fixes an infinite loop error and a false auto-correction behavior for `Layout/EndAlignment`
when using operator methods and `EnforcedStyleAlignWith: variable`.
This infinite loop error is due to an offense being registered but not auto-corrected.

`EnforcedStyleAlignWith: variable` enforces alignment to variable,
it should be auto-corrected to be aligned to variable even when operator method is used.
  • Loading branch information
koic committed Jul 14, 2021
1 parent 3e1cc1a commit c21ced8
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
@@ -0,0 +1 @@
* [#9928](https://github.com/rubocop/rubocop/issues/9928): Fix an infinite loop error and a false auto-correction behavior for `Layout/EndAlignment` when using operator methods and `EnforcedStyleAlignWith: variable`. ([@koic][])
9 changes: 8 additions & 1 deletion lib/rubocop/cop/layout/end_alignment.rb
Expand Up @@ -167,7 +167,8 @@ def alignment_node(node)
def alignment_node_for_variable_style(node)
return node.parent if node.case_type? && node.argument?

assignment = node.ancestors.find(&:assignment_or_similar?)
assignment = assignment_or_operator_method(node)

if assignment && !line_break_before_keyword?(assignment.source_range, node)
assignment
else
Expand All @@ -177,6 +178,12 @@ def alignment_node_for_variable_style(node)
node
end
end

def assignment_or_operator_method(node)
node.ancestors.find do |ancestor|
ancestor.assignment_or_similar? || ancestor.send_type? && ancestor.operator_method?
end
end
end
end
end
Expand Down
38 changes: 38 additions & 0 deletions spec/rubocop/cop/layout/end_alignment_spec.rb
Expand Up @@ -301,6 +301,44 @@ module Test
include_examples 'aligned', 'puts 1; while', 'Test', ' end'
include_examples 'aligned', 'puts 1; until', 'Test', ' end'
include_examples 'aligned', 'puts 1; case', 'a when b', ' end'

it 'register an offense when using `+` operator method and `end` is not aligned' do
expect_offense(<<~RUBY)
variable + if condition
foo
else
bar
end
^^^ `end` at 5, 11 is not aligned with `variable + if` at 1, 0.
RUBY

expect_correction(<<~RUBY)
variable + if condition
foo
else
bar
end
RUBY
end

it 'register an offense when using `-` operator method and `end` is not aligned' do
expect_offense(<<~RUBY)
variable - if condition
foo
else
bar
end
^^^ `end` at 5, 11 is not aligned with `variable - if` at 1, 0.
RUBY

expect_correction(<<~RUBY)
variable - if condition
foo
else
bar
end
RUBY
end
end

context 'correct + opposite' do
Expand Down

0 comments on commit c21ced8

Please sign in to comment.