Skip to content

Commit

Permalink
[Fix rubocop#4491] Prevent bad auto-correct in Style/EmptyElse for …
Browse files Browse the repository at this point in the history
…nested `if`

See rubocop#4491.

Reproduce
======

```ruby
if cond
  if cond2
    some
  else
  end
end
```

```bash
$ rubocop -a --only EmptyElse
Inspecting 1 file
E

Offenses:

test.rb:4:3: C: [Corrected] Redundant else-clause.
  else
  ^^^^
test.rb:5:1: E: unexpected token $end
(Using Ruby 2.1 parser; configure using TargetRubyVersion parameter, under AllCops)

1 file inspected, 2 offenses detected, 1 offense corrected

$ cat test.rb
if cond
  if cond2
    some
  end
```

This change fixes the bug.
  • Loading branch information
pocke committed Jun 10, 2017
1 parent 9ee1971 commit 95acb81
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* [#4451](https://github.com/bbatsov/rubocop/issues/4451): Make `Style/AndOr` cop aware of comparison methods. ([@drenmi][])
* [#4457](https://github.com/bbatsov/rubocop/pull/4457): Fix false negative in `Lint/Void` with initialize and setter methods. ([@pocke][])
* [#4418](https://github.com/bbatsov/rubocop/issues/4418): Register an offense in `Style/ConditionalAssignment` when the assignment line is the longest line, and it does not exceed the max line length. ([@rrosenblum][])
* [#4491](https://github.com/bbatsov/rubocop/issues/4491): Prevent bad auto-correct in `Style/EmptyElse` for nested `if`. ([@pocke][])

### Changes

Expand Down
1 change: 1 addition & 0 deletions lib/rubocop/cop/style/empty_else.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def autocorrect(node)
end

def base_if_node(node)
return node unless node.case_type? || node.elsif?
node.each_ancestor(:if).find { |parent| parent.loc.end } || node
end

Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/empty_else_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,27 @@
expect_no_offenses('if cond; foo end')
end
end

context 'in an if-statement' do
let(:source) { <<-RUBY.strip_indent }
if cond
if cond2
something
else
end
end
RUBY
let(:corrected_source) { <<-RUBY.strip_indent }
if cond
if cond2
something
end
end
RUBY

it_behaves_like 'auto-correct', 'if'
it_behaves_like 'offense registration'
end
end

context 'given an unless-statement' do
Expand Down

0 comments on commit 95acb81

Please sign in to comment.