Skip to content

Commit ba199d6

Browse files
committed
Update Rails/Pluck to be aware of numblocks.
1 parent 6420226 commit ba199d6

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#631](https://github.com/rubocop/rubocop-rails/pull/631): Update `Rails/Pluck` to be aware of numblocks. ([@sammiya][])

lib/rubocop/cop/rails/pluck.rb

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,34 +21,42 @@ class Pluck < Base
2121
extend AutoCorrector
2222
extend TargetRailsVersion
2323

24-
MSG = 'Prefer `pluck(:%<value>s)` over `%<method>s { |%<argument>s| %<element>s[:%<value>s] }`.'
24+
MSG = 'Prefer `pluck(:%<value>s)` over `%<current>s`.'
2525

2626
minimum_target_rails_version 5.0
2727

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

3232
def on_block(node)
33-
pluck_candidate?(node) do |method, argument, element, value|
34-
next unless argument == element
33+
pluck_candidate?(node) do |argument, element, value|
34+
match = if node.block_type?
35+
argument.children.first.source.to_sym == element
36+
else # numblock
37+
argument == 1 && element == :_1
38+
end
39+
next unless match
3540

36-
message = message(method, argument, element, value)
41+
message = message(value, node)
3742

3843
add_offense(offense_range(node), message: message) do |corrector|
3944
corrector.replace(offense_range(node), "pluck(:#{value})")
4045
end
4146
end
4247
end
48+
alias on_numblock on_block
4349

4450
private
4551

4652
def offense_range(node)
4753
node.send_node.loc.selector.join(node.loc.end)
4854
end
4955

50-
def message(method, argument, element, value)
51-
format(MSG, method: method, argument: argument, element: element, value: value)
56+
def message(value, node)
57+
current = offense_range(node).source
58+
59+
format(MSG, value: value, current: current)
5260
end
5361
end
5462
end

spec/rubocop/cop/rails/pluck_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@
3131
RUBY
3232
end
3333
end
34+
35+
context 'when using Ruby 2.7 or newer', :ruby27 do
36+
context 'when using numbered parameter' do
37+
context "when `#{method}` can be replaced with `pluck`" do
38+
it 'registers an offense' do
39+
expect_offense(<<~RUBY, method: method)
40+
x.%{method} { _1[:foo] }
41+
^{method}^^^^^^^^^^^^^ Prefer `pluck(:foo)` over `%{method} { _1[:foo] }`.
42+
RUBY
43+
44+
expect_correction(<<~RUBY)
45+
x.pluck(:foo)
46+
RUBY
47+
end
48+
end
49+
end
50+
end
3451
end
3552

3653
context 'when using Rails 4.2 or older', :rails42 do

0 commit comments

Comments
 (0)