Skip to content

Commit 46f9485

Browse files
committed
[Fix rubocop#257] Fix an incorrect auto-correct for Performance/MapCompact
This PR fixes an incorrect auto-correct for `Performance/MapCompact` when using multi-line `collection.map { ... }.compact` as a method argument.
1 parent 7be4a0b commit 46f9485

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## master (unreleased)
44

5+
### Bug fixes
6+
7+
* [#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][])
8+
59
## 1.11.4 (2021-07-07)
610

711
### Bug fixes

lib/rubocop/cop/performance/map_compact.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def remove_compact_method(corrector, compact_node)
6666
chained_method = compact_node.parent
6767
compact_method_range = compact_node.loc.selector
6868

69-
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) &&
69+
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && chained_method.dot? &&
7070
!invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
7171
compact_method_range = range_by_whole_lines(compact_method_range, include_final_newline: true)
7272
else

spec/rubocop/cop/performance/map_compact_spec.rb

+17
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,23 @@
128128
RUBY
129129
end
130130

131+
it 'registers an offense when using multi-line `collection.map { ... }.compact` as a method argument' do
132+
expect_offense(<<~RUBY)
133+
do_something(
134+
collection.map { |item|
135+
^^^^^^^^^^^^ Use `filter_map` instead.
136+
}.compact
137+
)
138+
RUBY
139+
140+
expect_correction(<<~RUBY)
141+
do_something(
142+
collection.filter_map { |item|
143+
}
144+
)
145+
RUBY
146+
end
147+
131148
it 'registers an offense when using multiline `map { ... }.compact` and assigning to return value' do
132149
expect_offense(<<~RUBY)
133150
ret = collection.map do |item|

0 commit comments

Comments
 (0)