Sha256: 7341a0afa2d395b171f6cadda53cb80ad1a5f248debdb0668e41b971be261429

Contents?: true

Size: 1.4 KB

Versions: 17

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # Enforces the use of `ids` over `pluck(:id)` and `pluck(primary_key)`.
      #
      # @safety
      #   This cop is unsafe if the receiver object is not an Active Record object.
      #
      # @example
      #   # bad
      #   User.pluck(:id)
      #   user.posts.pluck(:id)
      #
      #   def self.user_ids
      #     pluck(primary_key)
      #   end
      #
      #   # good
      #   User.ids
      #   user.posts.ids
      #
      #   def self.user_ids
      #     ids
      #   end
      #
      class PluckId < Base
        include RangeHelp
        include ActiveRecordHelper
        extend AutoCorrector

        MSG = 'Use `ids` instead of `%<bad_method>s`.'
        RESTRICT_ON_SEND = %i[pluck].freeze

        def_node_matcher :pluck_id_call?, <<~PATTERN
          (send _ :pluck {(sym :id) (send nil? :primary_key)})
        PATTERN

        def on_send(node)
          return if !pluck_id_call?(node) || in_where?(node)

          range = offense_range(node)
          message = format(MSG, bad_method: range.source)

          add_offense(range, message: message) do |corrector|
            corrector.replace(offense_range(node), 'ids')
          end
        end

        private

        def offense_range(node)
          range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
        end
      end
    end
  end
end

Version data entries

17 entries across 16 versions & 4 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rails-2.20.0/lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.22.2 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.22.1 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.22.0 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.21.2 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.21.1 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.21.0 lib/rubocop/cop/rails/pluck_id.rb
mlh-rubocop-config-1.0.2 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.20.2/lib/rubocop/cop/rails/pluck_id.rb
fablicop-1.10.3 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.19.1/lib/rubocop/cop/rails/pluck_id.rb
fablicop-1.10.3 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.20.2/lib/rubocop/cop/rails/pluck_id.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rails-2.20.0/lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.20.2 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.20.1 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.20.0 lib/rubocop/cop/rails/pluck_id.rb
fablicop-1.10.2 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.19.1/lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.19.1 lib/rubocop/cop/rails/pluck_id.rb
rubocop-rails-2.19.0 lib/rubocop/cop/rails/pluck_id.rb