Sha256: 1212095c1b9b8c54c768020757206353aa92eee00907aadb0d787288f05da004

Contents?: true

Size: 1.87 KB

Versions: 5

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # 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.
      #
      # @example
      #   # 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)
      class Pluck < Base
        extend AutoCorrector
        extend TargetRailsVersion

        MSG = 'Prefer `pluck(:%<value>s)` over `%<current>s`.'

        minimum_target_rails_version 5.0

        def_node_matcher :pluck_candidate?, <<~PATTERN
          ({block numblock} (send _ {:map :collect}) $_argument (send (lvar $_element) :[] (sym $_value)))
        PATTERN

        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
        alias on_numblock on_block

        private

        def offense_range(node)
          node.send_node.loc.selector.join(node.loc.end)
        end

        def message(value, node)
          current = offense_range(node).source

          format(MSG, value: value, current: current)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rails-2.14.2/lib/rubocop/cop/rails/pluck.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rails-2.14.2/lib/rubocop/cop/rails/pluck.rb
rubocop-rails-2.14.2 lib/rubocop/cop/rails/pluck.rb
rubocop-rails-2.14.1 lib/rubocop/cop/rails/pluck.rb
rubocop-rails-2.14.0 lib/rubocop/cop/rails/pluck.rb