Skip to content

Commit

Permalink
Merge pull request #1390 from masato-bkn/fix_incorrect_autocorrect_fo…
Browse files Browse the repository at this point in the history
…r_rails_select_map

Fix an incorrect autocorrect for `Rails/SelectMap` when `select` has no receiver and method chains are used
  • Loading branch information
koic authored Dec 1, 2024
2 parents c3ddedf + 02ea37f commit e470d18
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 e470d18

Please sign in to comment.