Skip to content

Commit

Permalink
[Fix rubocop#257] Fix an incorrect auto-correct for `Performance/MapC…
Browse files Browse the repository at this point in the history
…ompact`

Fixes rubocop#257.

This PR fixes an incorrect auto-correct for `Performance/MapCompact` when
using multi-line `collection.map { ... }.compact` as a method argument.
  • Loading branch information
koic committed Aug 13, 2021
1 parent 7be4a0b commit 897e70d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#257](https://github.com/rubocop/rubocop-performance/issues/257): Fix an incorrect auto-correct for `Performance/MapCompact` when using multi-line `collection.map { ... }.compact` as a method argument. ([@koic][])

## 1.11.4 (2021-07-07)

### Bug fixes
Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Expand Up @@ -66,7 +66,7 @@ def remove_compact_method(corrector, compact_node)
chained_method = compact_node.parent
compact_method_range = compact_node.loc.selector

if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) &&
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && chained_method.dot? &&
!invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
compact_method_range = range_by_whole_lines(compact_method_range, include_final_newline: true)
else
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Expand Up @@ -128,6 +128,23 @@
RUBY
end

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

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

it 'registers an offense when using multiline `map { ... }.compact` and assigning to return value' do
expect_offense(<<~RUBY)
ret = collection.map do |item|
Expand Down

0 comments on commit 897e70d

Please sign in to comment.