From 8c2d8dbfb57bbf1087a17ce5ae145cc16e873df7 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 30 Nov 2023 17:17:13 +0900 Subject: [PATCH] [Fix #1189] Fix false negatives for `Rails/Pluck` Fixes #1189. This PR fixes false negatives for `Rails/Pluck` when using safe navigation method calls. --- changelog/fix_false_negatives_for_rails_pluck.md | 1 + lib/rubocop/cop/rails/pluck.rb | 2 +- spec/rubocop/cop/rails/pluck_spec.rb | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_false_negatives_for_rails_pluck.md diff --git a/changelog/fix_false_negatives_for_rails_pluck.md b/changelog/fix_false_negatives_for_rails_pluck.md new file mode 100644 index 0000000000..901d60c40a --- /dev/null +++ b/changelog/fix_false_negatives_for_rails_pluck.md @@ -0,0 +1 @@ +* [#1189](https://github.com/rubocop/rubocop-rails/issues/1189): Fix false negatives for `Rails/Pluck` when using safe navigation method calls. ([@koic][]) diff --git a/lib/rubocop/cop/rails/pluck.rb b/lib/rubocop/cop/rails/pluck.rb index ee10214853..a6094ad648 100644 --- a/lib/rubocop/cop/rails/pluck.rb +++ b/lib/rubocop/cop/rails/pluck.rb @@ -38,7 +38,7 @@ class Pluck < Base minimum_target_rails_version 5.0 def_node_matcher :pluck_candidate?, <<~PATTERN - ({block numblock} (send _ {:map :collect}) $_argument (send lvar :[] $_key)) + ({block numblock} (call _ {:map :collect}) $_argument (send lvar :[] $_key)) PATTERN def on_block(node) diff --git a/spec/rubocop/cop/rails/pluck_spec.rb b/spec/rubocop/cop/rails/pluck_spec.rb index 01ba5192d9..bf425980a1 100644 --- a/spec/rubocop/cop/rails/pluck_spec.rb +++ b/spec/rubocop/cop/rails/pluck_spec.rb @@ -16,6 +16,19 @@ end end + context "when safe navigation `#{method}` with symbol literal key can be replaced with `pluck`" do + it 'registers an offense' do + expect_offense(<<~RUBY, method: method) + x&.%{method} { |a| a[:foo] } + ^{method}^^^^^^^^^^^^^^^^ Prefer `pluck(:foo)` over `%{method} { |a| a[:foo] }`. + RUBY + + expect_correction(<<~RUBY) + x&.pluck(:foo) + RUBY + end + end + context "when `#{method}` with string literal key can be replaced with `pluck`" do it 'registers an offense' do expect_offense(<<~RUBY, method: method)