Skip to content

Commit 09737e4

Browse files
authored
Merge pull request rubocop#831 from koic/fix_a_false_positive_for_rails_pluck
Fix a false positive for `Rails/Pluck`
2 parents c4ab8aa + abbf838 commit 09737e4

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#831](https://github.com/rubocop/rubocop-rails/pull/831): Fix a false positive for `Rails/Pluck` when using block argument in `[]`. ([@koic][])

lib/rubocop/cop/rails/pluck.rb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,16 @@ class Pluck < Base
2626
minimum_target_rails_version 5.0
2727

2828
def_node_matcher :pluck_candidate?, <<~PATTERN
29-
({block numblock} (send _ {:map :collect}) $_argument (send (lvar $_element) :[] $_key))
29+
({block numblock} (send _ {:map :collect}) $_argument (send lvar :[] $_key))
3030
PATTERN
3131

3232
def on_block(node)
33-
pluck_candidate?(node) do |argument, element, key|
33+
pluck_candidate?(node) do |argument, key|
3434
match = if node.block_type?
35-
argument.children.first.source.to_sym == element
35+
block_argument = argument.children.first.source
36+
use_block_argument_in_key?(block_argument, key)
3637
else # numblock
37-
argument == 1 && element == :_1
38+
argument == 1 && use_block_argument_in_key?('_1', key)
3839
end
3940
next unless match
4041

@@ -50,6 +51,10 @@ def on_block(node)
5051

5152
private
5253

54+
def use_block_argument_in_key?(block_argument, key)
55+
key.each_descendant(:lvar).none? { |lvar| block_argument == lvar.source }
56+
end
57+
5358
def offense_range(node)
5459
node.send_node.loc.selector.join(node.loc.end)
5560
end

spec/rubocop/cop/rails/pluck_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@
5050
end
5151
end
5252

53+
context 'when the block argument is used in `[]`' do
54+
it 'does not register an offense' do
55+
expect_no_offenses(<<~RUBY)
56+
x.#{method} { |a| a[foo...a.to_someghing] }
57+
RUBY
58+
end
59+
end
60+
5361
context 'when using Ruby 2.7 or newer', :ruby27 do
5462
context 'when using numbered parameter' do
5563
context "when `#{method}` can be replaced with `pluck`" do
@@ -64,6 +72,14 @@
6472
RUBY
6573
end
6674
end
75+
76+
context 'when the numblock argument is used in `[]`' do
77+
it 'does not register an offense' do
78+
expect_no_offenses(<<~RUBY)
79+
x.#{method} { _1[foo..._1.to_someghing] }
80+
RUBY
81+
end
82+
end
6783
end
6884
end
6985
end

0 commit comments

Comments
 (0)