Skip to content

Commit

Permalink
Merge pull request #1122 from koic/fix_an_error_for_rails_select_map
Browse files Browse the repository at this point in the history
[Fix #1121] Fix an error for `Rails/SelectMap`
  • Loading branch information
koic authored Sep 21, 2023
2 parents e687c3f + 53f7d5d commit d3117ff
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 d3117ff

Please sign in to comment.