Skip to content

Commit e470d18

Browse files
authored
Merge pull request #1390 from masato-bkn/fix_incorrect_autocorrect_for_rails_select_map
Fix an incorrect autocorrect for `Rails/SelectMap` when `select` has no receiver and method chains are used
2 parents c3ddedf + 02ea37f commit e470d18

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/select_map.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def find_select_node(node, column_name)
5454

5555
# rubocop:disable Metrics/AbcSize
5656
def autocorrect(corrector, select_node, node, preferred_method)
57-
corrector.remove(select_node.loc.dot || node.loc.dot)
57+
corrector.remove(select_node.parent.loc.dot)
5858
corrector.remove(select_node.loc.selector.begin.join(select_node.source_range.end))
5959
corrector.replace(node.loc.selector.begin.join(node.source_range.end), preferred_method)
6060
end

spec/rubocop/cop/rails/select_map_spec.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
RUBY
4646
end
4747

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

59+
it 'registers an offense when using `select(:column_name).where(conditions).map(&:column_name)` without receiver' do
60+
expect_offense(<<~RUBY)
61+
select(:column_name).where(conditions).map(&:column_name)
62+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`.
63+
RUBY
64+
65+
expect_correction(<<~RUBY)
66+
where(conditions).pluck(:column_name)
67+
RUBY
68+
end
69+
5970
it 'handles safe navigation chain' do
6071
expect_offense(<<~RUBY)
6172
relation&.select(:column_name)&.map(&:column_name)

0 commit comments

Comments
 (0)