Skip to content

Commit

Permalink
[Fix rubocop#1121] Fix an error for Rails/SelectMap
Browse files Browse the repository at this point in the history
Fixes rubocop#1121.

This PR fixes an error for `Rails/SelectMap`
when using `select(:column_name).map(&:column_name)` without receiver model.
  • Loading branch information
koic committed Sep 15, 2023
1 parent a3711eb commit 53f7d5d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_rails_select_map.md
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
5 changes: 4 additions & 1 deletion lib/rubocop/cop/rails/select_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,13 @@ def find_select_node(node, column_name)
end
end

# rubocop:disable Metrics/AbcSize
def autocorrect(corrector, select_node, node, preferred_method)
corrector.remove(select_node.loc.dot.begin.join(select_node.source_range.end))
corrector.remove(select_node.loc.dot || node.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
# rubocop:enable Metrics/AbcSize

def match_column_name?(select_candidate, column_name)
return false unless select_candidate.arguments.one?
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/select_map_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@
RUBY
end

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

expect_correction(<<~RUBY)
pluck(:column_name)
RUBY
end

it 'does not register an offense when using `select(:mismatch_column_name).map(&:column_name)`' do
expect_no_offenses(<<~RUBY)
Model.select(:mismatch_column_name).map(&:column_name)
Expand Down

0 comments on commit 53f7d5d

Please sign in to comment.