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 8c2d8db
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 @@ -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)
Expand Down

0 comments on commit 8c2d8db

Please sign in to comment.