Skip to content

Commit

Permalink
Merge pull request #10461 from jonas054/10375_fix_unless_else_autocor…
Browse files Browse the repository at this point in the history
…rect

[Fix #10375] Defer auto-correction of nested unless/else
  • Loading branch information
koic committed Mar 20, 2022
2 parents ef61df5 + 6915fd3 commit b901a9f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_unless_else_autocorrect.md
@@ -0,0 +1 @@
* [#10375](https://github.com/rubocop/rubocop/pull/10375): Fix error for auto-correction of `unless`/`else` nested inside each other. ([@jonas054][])
4 changes: 4 additions & 0 deletions lib/rubocop/cop/style/unless_else.rb
Expand Up @@ -32,10 +32,14 @@ def on_if(node)
body_range = range_between_condition_and_else(node, node.condition)
else_range = range_between_else_and_end(node)

next if part_of_ignored_node?(node)

corrector.replace(node.loc.keyword, 'if')
corrector.replace(body_range, else_range.source)
corrector.replace(else_range, body_range.source)
end

ignore_node(node)
end

def range_between_condition_and_else(node, condition)
Expand Down
30 changes: 30 additions & 0 deletions spec/rubocop/cop/style/unless_else_spec.rb
Expand Up @@ -20,6 +20,36 @@
end
RUBY
end

context 'and nested unless with else' do
it 'registers offenses for both but corrects only the outer unless/else' do
expect_offense(<<~RUBY)
unless abc
^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
a
else
unless cde
^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
b
else
c
end
end
RUBY

expect_correction(<<~RUBY)
if abc
unless cde
b
else
c
end
else
a
end
RUBY
end
end
end

context 'unless with nested if-else' do
Expand Down

0 comments on commit b901a9f

Please sign in to comment.