Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Rails/SelectMap when select has …
Browse files Browse the repository at this point in the history
…no receiver and method chains are used

This commit fixes an incorrect autocorrect for `Rails/SelectMap` when `select` has no receiver and method chains are used between `select` and `map`, as follows:

Before autocorrect
```ruby
select(:column_name).where(conditions).map(&:column_name)
```

After autocorrect (syntax error)
```ruby
.where(conditions)pluck(:column_name)
```
  • Loading branch information
masato-bkn committed Dec 1, 2024
1 parent c3ddedf commit 02ea37f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_fix_an_incorrect_autocorrect_for.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1390](https://github.com/rubocop/rubocop-rails/pull/1390): Fix an incorrect autocorrect for `Rails/SelectMap` when `select` has no receiver and method chains are used. ([@masato-bkn][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/select_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def find_select_node(node, column_name)

# rubocop:disable Metrics/AbcSize
def autocorrect(corrector, select_node, node, preferred_method)
corrector.remove(select_node.loc.dot || node.loc.dot)
corrector.remove(select_node.parent.loc.dot)
corrector.remove(select_node.loc.selector.begin.join(select_node.source_range.end))
corrector.replace(node.loc.selector.begin.join(node.source_range.end), preferred_method)
end
Expand Down
13 changes: 12 additions & 1 deletion spec/rubocop/cop/rails/select_map_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
RUBY
end

it 'registers an offense when using `select(:column_name).map(&:column_name)` without receiver model' do
it 'registers an offense when using `select(:column_name).map(&:column_name)` without receiver' do
expect_offense(<<~RUBY)
select(:column_name).map(&:column_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`.
Expand All @@ -56,6 +56,17 @@
RUBY
end

it 'registers an offense when using `select(:column_name).where(conditions).map(&:column_name)` without receiver' do
expect_offense(<<~RUBY)
select(:column_name).where(conditions).map(&:column_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`.
RUBY

expect_correction(<<~RUBY)
where(conditions).pluck(:column_name)
RUBY
end

it 'handles safe navigation chain' do
expect_offense(<<~RUBY)
relation&.select(:column_name)&.map(&:column_name)
Expand Down

0 comments on commit 02ea37f

Please sign in to comment.