Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_map_compact_as_argument.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#556](https://github.com/rubocop/rubocop-performance/pull/556): Fix an incorrect autocorrect for `Performance/MapCompact` when used as an argument. ([@Starlexxx][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,18 @@ def on_send(node)

add_offense(range) do |corrector|
corrector.replace(map_node.loc.selector, 'filter_map')
remove_compact_method(corrector, map_node, node, node.parent)
remove_compact_method(corrector, map_node, node, chained_method(node))
end
end
alias on_csend on_send

private

def chained_method(compact_node)
parent = compact_node.parent
parent if parent&.call_type? && parent.receiver.equal?(compact_node)
end

def remove_compact_method(corrector, map_node, compact_node, chained_method)
compact_method_range = compact_node.loc.selector

Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,25 @@
RUBY
end

it 'registers an offense when a multiline `map do ... end.compact` is an argument of a dotted call' do
expect_offense(<<~RUBY)
Set.new(
collection.map do |item|
^^^^^^^^^^^^^ Use `filter_map` instead.
item.do_something
end.compact
)
RUBY

expect_correction(<<~RUBY)
Set.new(
collection.filter_map do |item|
item.do_something
end
)
RUBY
end

it 'registers an offense when using `map(&:do_something).compact.first` with single-line method calls' do
expect_offense(<<~RUBY)
collection.map(&:do_something).compact.first
Expand Down
Loading