Skip to content

Commit

Permalink
Fixes multi-line ReverseEach autocorrection
Browse files Browse the repository at this point in the history
When reverse and each are on separate lines, we end up autocorrecting
```ruby
foo.reverse.
  each { ... }
```
to
```ruby
foo.reverse_
  each { ... }
```
. With this change, we will instead update to
```ruby
foo.reverse_each { ... }
```
  • Loading branch information
siegfault committed May 15, 2020
1 parent 204ea8d commit aed79fe
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## master (unreleased)

### Bug fixes
* [#108](https://github.com/rubocop-hq/rubocop-performance/pull/108): Fix an incorrect autocorrect for `Performance/ReverseEach` when there is a newline between reverse and each. ([@joe-sharp][], [@dischorde][], [@siegfault][])

### New features

* [#77](https://github.com/rubocop-hq/rubocop-performance/issues/77): Add new `Performance/BindCall` cop. ([@koic][])
Expand Down Expand Up @@ -86,3 +89,6 @@
[@rrosenblum]: https://github.com/rrosenblum
[@splattael]: https://github.com/splattael
[@eugeneius]: https://github.com/eugeneius
[@joe-sharp]: https://github.com/joe-sharp
[@dischorde]: https://github.com/dischorde
[@siegfault]: https://github.com/siegfault
3 changes: 2 additions & 1 deletion lib/rubocop/cop/performance/reverse_each.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ def on_send(node)
end

def autocorrect(node)
->(corrector) { corrector.replace(node.loc.dot, UNDERSCORE) }
range = range_between(node.loc.dot.begin_pos, node.loc.selector.begin_pos)
->(corrector) { corrector.replace(range, UNDERSCORE) }
end
end
end
Expand Down
34 changes: 34 additions & 0 deletions spec/rubocop/cop/performance/reverse_each_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ def arr
RUBY
end

it 'registers an offense for a multi-line reverse.each' do
expect_offense(<<~RUBY)
def arr
[1, 2, 3]
end
arr.
reverse.
^^^^^^^^ Use `reverse_each` instead of `reverse.each`.
each { |e| puts e }
RUBY
end

it 'does not register an offense when reverse is used without each' do
expect_no_offenses('[1, 2, 3].reverse')
end
Expand Down Expand Up @@ -73,5 +86,26 @@ def arr
arr.reverse_each { |e| puts e }
RUBY
end

it 'corrects a multi-line reverse_each' do
new_source = autocorrect_source(<<~RUBY)
def arr
[1, 2]
end
arr.
reverse.
each { |e| puts e }
RUBY

expect(new_source).to eq(<<~RUBY)
def arr
[1, 2]
end
arr.
reverse_each { |e| puts e }
RUBY
end
end
end

0 comments on commit aed79fe

Please sign in to comment.