From 84d4b258848f469d3c640b35e7abebb8bc57a0e7 Mon Sep 17 00:00:00 2001 From: fatkodima Date: Sun, 22 Sep 2024 15:01:24 +0300 Subject: [PATCH] Change `Rails/SelectMap` to handle safe navigation operators --- ...lect_map_safe_navigation_handle_safe_navigation.md | 1 + lib/rubocop/cop/rails/select_map.rb | 3 ++- spec/rubocop/cop/rails/select_map_spec.rb | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 changelog/change_select_map_safe_navigation_handle_safe_navigation.md diff --git a/changelog/change_select_map_safe_navigation_handle_safe_navigation.md b/changelog/change_select_map_safe_navigation_handle_safe_navigation.md new file mode 100644 index 0000000000..e6a8cf2090 --- /dev/null +++ b/changelog/change_select_map_safe_navigation_handle_safe_navigation.md @@ -0,0 +1 @@ +* [#1195](https://github.com/rubocop/rubocop-rails/issues/1195): Change `Rails/SelectMap` to handle safe navigation operators. ([@fatkodima][]) diff --git a/lib/rubocop/cop/rails/select_map.rb b/lib/rubocop/cop/rails/select_map.rb index ede846d915..c988096df1 100644 --- a/lib/rubocop/cop/rails/select_map.rb +++ b/lib/rubocop/cop/rails/select_map.rb @@ -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 diff --git a/spec/rubocop/cop/rails/select_map_spec.rb b/spec/rubocop/cop/rails/select_map_spec.rb index 767516e4d6..de609cb06c 100644 --- a/spec/rubocop/cop/rails/select_map_spec.rb +++ b/spec/rubocop/cop/rails/select_map_spec.rb @@ -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)