diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b8d8417fc..b30c2529eb 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 { ... }.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..48056ddbe1 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 { ... }.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|