Skip to content

Commit

Permalink
Merge pull request #237 from koic/fix_incorrect_autocorrect_for_perfo…
Browse files Browse the repository at this point in the history
…rmance_map_compact

[Fix #236] Fix an incorrect auto-correct for `Performance/MapCompact`
  • Loading branch information
koic authored Apr 25, 2021
2 parents d51f1c7 + f6e59b5 commit 7ea001e
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#236](https://github.com/rubocop/rubocop-performance/issues/236): Fix an incorrect auto-correct for `Performance/MapCompact` when using multi-line leading dot method calls. ([@koic][])

## 1.11.0 (2021-04-22)

### New features
Expand Down
14 changes: 13 additions & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,19 @@ def on_send(node)
add_offense(range) do |corrector|
corrector.replace(map_node.loc.selector, 'filter_map')
corrector.remove(compact_loc.dot)
corrector.remove(compact_loc.selector)
corrector.remove(compact_method_range(node))
end
end

private

def compact_method_range(compact_node)
compact_method_range = compact_node.loc.selector

if compact_node.multiline?
range_by_whole_lines(compact_method_range, include_final_newline: true)
else
compact_method_range
end
end
end
Expand Down
40 changes: 40 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,46 @@
RUBY
end

it 'registers an offense when using `map.compact.first` with single-line method calls' do
expect_offense(<<~RUBY)
collection.map { |item| item.do_something }.compact.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
RUBY

expect_correction(<<~RUBY)
collection.filter_map { |item| item.do_something }.first
RUBY
end

it 'registers an offense when using `map.compact.first` with multi-line leading dot method calls' do
expect_offense(<<~RUBY)
collection
.map { |item| item.do_something }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
.compact
.first
RUBY

expect_correction(<<~RUBY)
collection
.filter_map { |item| item.do_something }
.first
RUBY
end

it 'registers an offense when using `map.compact.first` and there is a line break after `map.compact`' do
expect_offense(<<~RUBY)
collection.map { |item| item.do_something }.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
.first
RUBY

expect_correction(<<~RUBY)
collection.filter_map { |item| item.do_something }
.first
RUBY
end

it 'does not register an offense when using `collection.map(&:do_something).compact!`' do
expect_no_offenses(<<~RUBY)
collection.map(&:do_something).compact!
Expand Down

0 comments on commit 7ea001e

Please sign in to comment.