Class: RuboCop::Cop::Rails::Pluck

Inherits:
RuboCop::Cop show all
Extended by:
TargetRailsVersion
Defined in:
lib/rubocop/cop/rails/pluck.rb

Overview

This cop enforces the use of ‘pluck` over `map`.

‘pluck` can be used instead of `map` to extract a single key from each element in an enumerable. When called on an Active Record relation, it results in a more efficient query that only selects the necessary key.

Examples:

# bad
Post.published.map { |post| post[:title] }
[{ a: :b, c: :d }].collect { |el| el[:a] }

# good
Post.published.pluck(:title)
[{ a: :b, c: :d }].pluck(:a)

Constant Summary collapse

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

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#autocorrect(node) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rails/pluck.rb', line 39

def autocorrect(node)
  _method, _argument, _element, value = pluck_candidate?(node)

  lambda do |corrector|
    corrector.replace(offense_range(node), "pluck(:#{value})")
  end
end

#on_block(node) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/rubocop/cop/rails/pluck.rb', line 31

def on_block(node)
  pluck_candidate?(node) do |method, argument, element, value|
    next unless argument == element

    add_offense(node, location: offense_range(node), message: message(method, argument, element, value))
  end
end