Skip to content

Commit

Permalink
Merge pull request #248 from koic/fix_incorrect_autocorrect_for_perfo…
Browse files Browse the repository at this point in the history
…rmance_map_compact_cop

[Fix #247] Fix an incorrect auto-correct for `Performance/MapCompact`
  • Loading branch information
koic committed May 21, 2021
2 parents 1fff69f + e1b1316 commit 9b8d2e9
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#247](https://github.com/rubocop/rubocop-performance/issues/247): Fix an incorrect auto-correct for `Performance/MapCompact` when using multi-line trailing dot method calls. ([@koic][])

### Changes

* [#245](https://github.com/rubocop/rubocop-performance/issues/245): Mark `Performance/DeletePrefix` and `Performance/DeleteSuffix` as unsafe. ([@koic][])
Expand Down
11 changes: 6 additions & 5 deletions lib/rubocop/cop/performance/map_compact.rb
Expand Up @@ -56,23 +56,24 @@ def on_send(node)

add_offense(range) do |corrector|
corrector.replace(map_node.loc.selector, 'filter_map')
corrector.remove(compact_loc.dot)
corrector.remove(compact_method_range(node))
remove_compact_method(corrector, node)
end
end

private

def compact_method_range(compact_node)
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) &&
!invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
range_by_whole_lines(compact_method_range, include_final_newline: true)
compact_method_range = range_by_whole_lines(compact_method_range, include_final_newline: true)
else
compact_method_range
corrector.remove(compact_node.loc.dot)
end

corrector.remove(compact_method_range)
end

def invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Expand Up @@ -73,6 +73,22 @@
RUBY
end

it 'registers an offense when using `map.compact.first` with multi-line trailing dot method calls' do
expect_offense(<<~RUBY)
collection.
map { |item| item.do_something }.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `filter_map` instead.
compact.
first
RUBY

expect_correction(<<~RUBY)
collection.
filter_map { |item| item.do_something }.
first
RUBY
end

it 'registers an offense when using `map.compact.first` and there is a line break after `map.compact`' do
expect_offense(<<~RUBY)
collection.map { |item| item.do_something }.compact
Expand Down

0 comments on commit 9b8d2e9

Please sign in to comment.