Skip to content

Commit

Permalink
Fix Performance/MapCompact autocorrect causing invalid syntax
Browse files Browse the repository at this point in the history
This commit fixes the issue when `Performance/MapCompact` auto-correction
fails to detect the argument block of an assignment method so it deletes
the block ending (i.e. `end` or `}`) when `map { ... }.compact` is
multiline.

Before

```ruby
object.new_collection = collection.map do |item|
end.compact

object.new_collection = collection.filter_map do |item|
```

After

```ruby
object.new_collection = collection.map do |item|
end.compact

object.new_collection = collection.filter_map do |item|
end
```
  • Loading branch information
QQism committed Jun 3, 2022
1 parent 7c1d7d5 commit 3865688
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#291](https://github.com/rubocop/rubocop-performance/pull/291): Fix `Performance/MapCompact` autocorrect causing invalid syntax when using multiline `map { ... }.compact` as an argument for an assignment method. ([@QQism][])

## 1.14.0 (2022-05-24)

### Bug fixes
Expand Down Expand Up @@ -362,3 +366,4 @@
[@mvz]: https://github.com/mvz
[@leoarnold]: https://github.com/leoarnold
[@ydah]: https://github.com/ydah
[@QQism]: https://github.com/QQism
2 changes: 1 addition & 1 deletion lib/rubocop/cop/performance/map_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def map_method_and_compact_method_on_same_line?(map_node, compact_node)
end

def invoke_method_after_map_compact_on_same_line?(compact_node, chained_method)
compact_node.loc.selector.line == chained_method.loc.selector.line
compact_node.loc.selector.line == chained_method.loc.last_line
end

def compact_method_with_final_newline_range(compact_method_range)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/performance/map_compact_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,19 @@
RUBY
end

it 'registers an offense when using multiline `map { ... }.compact` as an argument of an assignment method' do
expect_offense(<<~RUBY)
object.new_collection = collection.map do |item|
^^^^^^^^^^^^^ Use `filter_map` instead.
end.compact
RUBY

expect_correction(<<~RUBY)
object.new_collection = collection.filter_map do |item|
end
RUBY
end

it 'does not register an offense when using `collection.map(&:do_something).compact!`' do
expect_no_offenses(<<~RUBY)
collection.map(&:do_something).compact!
Expand Down

0 comments on commit 3865688

Please sign in to comment.