From d16456865c002c5f0b81ecbc7413dc49e2fa017e Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 13 Aug 2021 10:49:46 +0900 Subject: [PATCH] [Fix #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 { |item| }.compact` as a method argument. --- CHANGELOG.md | 4 ++++ lib/rubocop/cop/performance/map_compact.rb | 2 +- .../rubocop/cop/performance/map_compact_spec.rb | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b8d8417fc..3cfb7fd32b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 { |item| }.compact` as a method argument. ([@koic][]) + ## 1.11.4 (2021-07-07) ### Bug fixes diff --git a/lib/rubocop/cop/performance/map_compact.rb b/lib/rubocop/cop/performance/map_compact.rb index 705c723da7..4082319601 100644 --- a/lib/rubocop/cop/performance/map_compact.rb +++ b/lib/rubocop/cop/performance/map_compact.rb @@ -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 diff --git a/spec/rubocop/cop/performance/map_compact_spec.rb b/spec/rubocop/cop/performance/map_compact_spec.rb index 0eac98dff3..ef38e3dd32 100644 --- a/spec/rubocop/cop/performance/map_compact_spec.rb +++ b/spec/rubocop/cop/performance/map_compact_spec.rb @@ -128,6 +128,23 @@ RUBY end + it 'registers an offense when using multi-line `collection.map { |item| }.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|