Skip to content

Commit 60dbe30

Browse files
committed
[Fix rubocop#309] Fix an error for Performance/MapCompact
Fixes rubocop#309. This PR fixes an error for `Performance/MapCompact` when using `map(&:do_something).compact` and there is a line break after `map.compact` and assigning with `||=`.
1 parent 3dd06b5 commit 60dbe30

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#309](https://github.com/rubocop/rubocop-performance/issues/309): Fix an error for `Performance/MapCompact` when using `map(&:do_something).compact` and there is a line break after `map.compact` and assigning with `||=`. ([@koic][])

lib/rubocop/cop/performance/map_compact.rb

+5-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def on_send(node)
6767
def remove_compact_method(corrector, map_node, compact_node, chained_method)
6868
compact_method_range = compact_node.loc.selector
6969

70-
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && chained_method.dot? &&
70+
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && use_dot?(chained_method) &&
7171
!map_method_and_compact_method_on_same_line?(map_node, compact_node) &&
7272
!invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
7373
compact_method_range = compact_method_with_final_newline_range(compact_method_range)
@@ -78,6 +78,10 @@ def remove_compact_method(corrector, map_node, compact_node, chained_method)
7878
corrector.remove(compact_method_range)
7979
end
8080

81+
def use_dot?(node)
82+
node.respond_to?(:dot?) && node.dot?
83+
end
84+
8185
def map_method_and_compact_method_on_same_line?(map_node, compact_node)
8286
compact_node.loc.selector.line == map_node.loc.selector.line
8387
end

spec/rubocop/cop/performance/map_compact_spec.rb

+14
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,20 @@
119119
RUBY
120120
end
121121

122+
it 'registers an offense when using `map(&:do_something).compact` and there is a line break after' \
123+
'`map.compact` and assigning with `||=`' do
124+
expect_offense(<<~RUBY)
125+
foo[1] ||= collection
126+
.map(&:do_something).compact
127+
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
128+
RUBY
129+
130+
expect_correction(<<~RUBY)
131+
foo[1] ||= collection
132+
.filter_map(&:do_something)
133+
RUBY
134+
end
135+
122136
it 'registers an offense when using `map { ... }.compact.first` with single-line method calls' do
123137
expect_offense(<<~RUBY)
124138
collection.map { |item| item.do_something }.compact.first

0 commit comments

Comments
 (0)