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..a8be8c1b44 100644 --- a/spec/rubocop/cop/rails/pluck_spec.rb +++ b/spec/rubocop/cop/rails/pluck_spec.rb @@ -42,6 +42,19 @@ end end + context "when safe navigation `#{method}` with method call key can be replaced with `pluck`" do + it 'registers an offense' do + expect_offense(<<~RUBY, method: method) + x&.%{method} { |a| a[obj.do_something] } + ^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `pluck(obj.do_something)` over `%{method} { |a| a[obj.do_something] }`. + RUBY + + expect_correction(<<~RUBY) + x&.pluck(obj.do_something) + RUBY + end + end + context 'when the block argument is unused' do it 'does not register an offense' do expect_no_offenses(<<~RUBY)