Sha256: aa605469764466a98e2b315d9f220d4093c4a6dff896e4c5c5ac86566e36431a

Contents?: true

Size: 1.53 KB

Versions: 11

Compression:

Stored size: 1.53 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 = [:all, :where, :not].freeze

        def on_send(node)
          receiver, second_method, _selector = *node
          return unless second_method == :each
          return if receiver.nil?

          _model, first_method = *receiver
          return unless SCOPE_METHODS.include?(first_method)
          return if method_chain(node).any? { |m| ignored_by_find_each?(m) }

          add_offense(node, node.loc.selector, MSG)
        end

        def autocorrect(node)
          each_loc = node.loc.selector

          ->(corrector) { corrector.replace(each_loc, 'find_each') }
        end

        private

        def method_chain(node)
          if (node.send_type? || node.block_type?) && !node.receiver.nil?
            if node.parent
              method_chain(node.parent) << node.method_name
            else
              [node.method_name]
            end
          else
            []
          end
        end

        def ignored_by_find_each?(relation_method)
          # Active Record's #find_each ignores various extra parameters
          [:order, :limit, :select].include?(relation_method)
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_each.rb
rubocop-0.46.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.45.0 lib/rubocop/cop/rails/find_each.rb
rubocop-0.44.1 lib/rubocop/cop/rails/find_each.rb
rubocop-0.44.0 lib/rubocop/cop/rails/find_each.rb