Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #10375] Defer auto-correction of nested unless/else #10461

Merged
merged 1 commit into from Mar 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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