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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, 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 `%<current>s`.'

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#on_block(node) ⇒ Object Also known as: on_numblock



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/rails/pluck.rb', line 32

def on_block(node)
  pluck_candidate?(node) do |argument, element, value|
    match = if node.block_type?
              argument.children.first.source.to_sym == element
            else # numblock
              argument == 1 && element == :_1
            end
    next unless match

    message = message(value, node)

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