Skip to content

Commit

Permalink
Merge pull request #1370 from fatkodima/select_map-safe-navigation
Browse files Browse the repository at this point in the history
Change `Rails/SelectMap` to handle safe navigation operators
  • Loading branch information
koic committed Sep 23, 2024
2 parents 1b7292e + 84d4b25 commit 490e9e8
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1195](https://github.com/rubocop/rubocop-rails/issues/1195): Change `Rails/SelectMap` to handle safe navigation operators. ([@fatkodima][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/rails/select_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ def on_send(node)
autocorrect(corrector, select_node, node, preferred_method)
end
end
alias on_csend on_send

private

def find_select_node(node, column_name)
node.descendants.detect do |select_candidate|
next if !select_candidate.send_type? || !select_candidate.method?(:select)
next if !select_candidate.call_type? || !select_candidate.method?(:select)

match_column_name?(select_candidate, column_name)
end
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 @@ -56,6 +56,17 @@
RUBY
end

it 'handles safe navigation chain' do
expect_offense(<<~RUBY)
relation&.select(:column_name)&.map(&:column_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`.
RUBY

expect_correction(<<~RUBY)
relation&.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 490e9e8

Please sign in to comment.