Skip to content

Commit

Permalink
[Fix #238] Fix an incorrect auto-correct for Performance/MapCompact
Browse files Browse the repository at this point in the history
Fixes #238.

This PR fixes an incorrect auto-correct for `Performance/MapCompact`
when invoking a method after `map { ... }.compact` on the same line.
  • Loading branch information
koic committed May 4, 2021
1 parent 71d2ccb commit 0320422
Show file tree
Hide file tree
Showing 3 changed files with 37 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

* [#238](https://github.com/rubocop/rubocop-performance/issues/238): Fix an incorrect auto-correct for `Performance/MapCompact` when invoking a method after `map { ... }.compact` on the same line. ([@koic][])

## 1.11.1 (2021-05-02)

### Bug fixes
Expand Down
8 changes: 7 additions & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,20 @@ def on_send(node)
private

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

if compact_node.multiline?
if compact_node.multiline? &&
chained_method && !invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
range_by_whole_lines(compact_method_range, include_final_newline: true)
else
compact_method_range
end
end

def invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
compact_node.loc.selector.line == chained_method.loc.selector.line
end
end
end
end
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,32 @@
RUBY
end

it 'registers an offense when using `map { ... }.compact`' do
expect_offense(<<~RUBY)
collection.map { |item|
^^^^^^^^^^^^ Use `filter_map` instead.
}.compact
RUBY

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

it 'registers an offense when invoking a method after `map { ... }.compact`' do
expect_offense(<<~RUBY)
collection.map { |item|
^^^^^^^^^^^^ Use `filter_map` instead.
}.compact.do_something
RUBY

expect_correction(<<~RUBY)
collection.filter_map { |item|
}.do_something
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 0320422

Please sign in to comment.