Sha256: adf39da878d7a32cb65fdfb5b677814a5683eae27e8fa48aeb4cea20ada50cd3

Contents?: true

Size: 1.22 KB

Versions: 14

Compression:

Stored size: 1.22 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop is used to identify usages of `all.each` and
      # change them to use `all.find_each` instead.
      #
      # @example
      #   # bad
      #   User.all.each
      #
      #   # good
      #   User.all.find_each
      class FindEach < Cop
        MSG = 'Use `find_each` instead of `each`.'.freeze

        SCOPE_METHODS = %i[all where not].freeze
        IGNORED_METHODS = %i[order limit select].freeze

        def on_send(node)
          return unless node.receiver && node.method?(:each)

          return unless SCOPE_METHODS.include?(node.receiver.method_name)
          return if method_chain(node).any? { |m| ignored_by_find_each?(m) }

          add_offense(node, location: :selector)
        end

        def autocorrect(node)
          ->(corrector) { corrector.replace(node.loc.selector, 'find_each') }
        end

        private

        def method_chain(node)
          [*node.ancestors, node].map(&:method_name)
        end

        def ignored_by_find_each?(relation_method)
          # Active Record's #find_each ignores various extra parameters
          IGNORED_METHODS.include?(relation_method)
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
rubocop-0.58.2 lib/rubocop/cop/rails/find_each.rb
rubocop-0.58.1 lib/rubocop/cop/rails/find_each.rb
rubocop-0.58.0 lib/rubocop/cop/rails/find_each.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/rails/find_each.rb
rubocop-0.57.2 lib/rubocop/cop/rails/find_each.rb
rubocop-0.57.1 lib/rubocop/cop/rails/find_each.rb
rubocop-0.57.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.56.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.55.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.54.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.53.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.52.1 lib/rubocop/cop/rails/find_each.rb
rubocop-0.52.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.51.0 lib/rubocop/cop/rails/find_each.rb