Skip to content

Commit d3117ff

Browse files
authored
Merge pull request #1122 from koic/fix_an_error_for_rails_select_map
[Fix #1121] Fix an error for `Rails/SelectMap`
2 parents e687c3f + 53f7d5d commit d3117ff

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1121](https://github.com/rubocop/rubocop-rails/issues/1121): Fix an error for `Rails/SelectMap` when using `select(:column_name).map(&:column_name)` without receiver model. ([@koic][])

lib/rubocop/cop/rails/select_map.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,13 @@ def find_select_node(node, column_name)
5151
end
5252
end
5353

54+
# rubocop:disable Metrics/AbcSize
5455
def autocorrect(corrector, select_node, node, preferred_method)
55-
corrector.remove(select_node.loc.dot.begin.join(select_node.source_range.end))
56+
corrector.remove(select_node.loc.dot || node.loc.dot)
57+
corrector.remove(select_node.loc.selector.begin.join(select_node.source_range.end))
5658
corrector.replace(node.loc.selector.begin.join(node.source_range.end), preferred_method)
5759
end
60+
# rubocop:enable Metrics/AbcSize
5861

5962
def match_column_name?(select_candidate, column_name)
6063
return false unless select_candidate.arguments.one?

spec/rubocop/cop/rails/select_map_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@
4545
RUBY
4646
end
4747

48+
it 'registers an offense when using `select(:column_name).map(&:column_name)` without receiver model' do
49+
expect_offense(<<~RUBY)
50+
select(:column_name).map(&:column_name)
51+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`.
52+
RUBY
53+
54+
expect_correction(<<~RUBY)
55+
pluck(:column_name)
56+
RUBY
57+
end
58+
4859
it 'does not register an offense when using `select(:mismatch_column_name).map(&:column_name)`' do
4960
expect_no_offenses(<<~RUBY)
5061
Model.select(:mismatch_column_name).map(&:column_name)

0 commit comments

Comments
 (0)