Skip to content

Commit

Permalink
[Fix rubocop#1189] Fix false negatives for Rails/Pluck
Browse files Browse the repository at this point in the history
Fixes rubocop#1189.

This PR fixes false negatives for `Rails/Pluck`
when using safe navigation method calls.
  • Loading branch information
koic committed Nov 30, 2023
1 parent a27f6df commit 8fd329e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_false_negatives_for_rails_pluck.md
Original file line number Diff line number Diff line change
@@ -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][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/pluck.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rails/pluck_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 8fd329e

Please sign in to comment.