Skip to content

Commit

Permalink
[Fix rubocop#309] Fix an error for Performance/MapCompact
Browse files Browse the repository at this point in the history
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 `||=`.
  • Loading branch information
koic committed Nov 14, 2022
1 parent 3dd06b5 commit 60dbe30
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_performance_map_compact.md
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def on_send(node)
def remove_compact_method(corrector, map_node, compact_node, chained_method)
compact_method_range = compact_node.loc.selector

if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && chained_method.dot? &&
if compact_node.multiline? && chained_method&.loc.respond_to?(:selector) && use_dot?(chained_method) &&
!map_method_and_compact_method_on_same_line?(map_node, compact_node) &&
!invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
compact_method_range = compact_method_with_final_newline_range(compact_method_range)
Expand All @@ -78,6 +78,10 @@ def remove_compact_method(corrector, map_node, compact_node, chained_method)
corrector.remove(compact_method_range)
end

def use_dot?(node)
node.respond_to?(:dot?) && node.dot?
end

def map_method_and_compact_method_on_same_line?(map_node, compact_node)
compact_node.loc.selector.line == map_node.loc.selector.line
end
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,20 @@
RUBY
end

it 'registers an offense when using `map(&:do_something).compact` and there is a line break after' \
'`map.compact` and assigning with `||=`' do
expect_offense(<<~RUBY)
foo[1] ||= collection
.map(&:do_something).compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
RUBY

expect_correction(<<~RUBY)
foo[1] ||= collection
.filter_map(&:do_something)
RUBY
end

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

0 comments on commit 60dbe30

Please sign in to comment.