From aed79febd6d3d601fb809bd652ee17112fd7480a Mon Sep 17 00:00:00 2001 From: Michael Siegfried Date: Fri, 15 May 2020 11:30:43 -0700 Subject: [PATCH] Fixes multi-line ReverseEach autocorrection 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 { ... } ``` --- CHANGELOG.md | 6 ++++ lib/rubocop/cop/performance/reverse_each.rb | 3 +- .../cop/performance/reverse_each_spec.rb | 34 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6443446f2f..1521db6118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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][]) @@ -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 diff --git a/lib/rubocop/cop/performance/reverse_each.rb b/lib/rubocop/cop/performance/reverse_each.rb index 66a1f99485..09a8214123 100644 --- a/lib/rubocop/cop/performance/reverse_each.rb +++ b/lib/rubocop/cop/performance/reverse_each.rb @@ -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 diff --git a/spec/rubocop/cop/performance/reverse_each_spec.rb b/spec/rubocop/cop/performance/reverse_each_spec.rb index 75389f13db..396952b90f 100644 --- a/spec/rubocop/cop/performance/reverse_each_spec.rb +++ b/spec/rubocop/cop/performance/reverse_each_spec.rb @@ -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 @@ -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