Class: RuboCop::Cop::Rails::SelectMap

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rails/select_map.rb

Overview

Checks for uses of ‘select(:column_name)` with `map(&:column_name)`. These can be replaced with `pluck(:column_name)`.

There also should be some performance improvement since it skips instantiating the model class for matches.

Examples:

# bad
Model.select(:column_name).map(&:column_name)

# good
Model.pluck(:column_name)

Constant Summary collapse

MSG =
'Use `%<preferred_method>s` instead of `select` with `%<map_method>s`.'
RESTRICT_ON_SEND =
%i[map collect].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rubocop/cop/rails/select_map.rb', line 29

def on_send(node)
  return unless node.first_argument

  column_name = node.first_argument.source.delete_prefix('&:')
  return unless (select_node = find_select_node(node, column_name))

  offense_range = select_node.loc.selector.begin.join(node.source_range.end)
  preferred_method = "pluck(:#{column_name})"
  message = format(MSG, preferred_method: preferred_method, map_method: node.method_name)

  add_offense(offense_range, message: message) do |corrector|
    autocorrect(corrector, select_node, node, preferred_method)
  end
end