Sha256: c46c63766c0b9d91a0d302248edf01b202df29b39c1de145c5789f8f025d5f93

Contents?: true

Size: 1.3 KB

Versions: 5

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop checks for multiple scopes in a model that have the same `where` clause. This
      # often means you copy/pasted a scope, updated the name, and forgot to change the condition.
      #
      # @example
      #
      #   # bad
      #   scope :visible, -> { where(visible: true) }
      #   scope :hidden, -> { where(visible: true) }
      #
      #   # good
      #   scope :visible, -> { where(visible: true) }
      #   scope :hidden, -> { where(visible: false) }
      #
      class DuplicateScope < Base
        include ClassSendNodeHelper

        MSG = 'Multiple scopes share this same where clause.'

        def_node_matcher :scope, <<~PATTERN
          (send nil? :scope _ $...)
        PATTERN

        def on_class(class_node)
          offenses(class_node).each do |node|
            add_offense(node)
          end
        end

        private

        def offenses(class_node)
          class_send_nodes(class_node).select { |node| scope(node) }
                                      .group_by { |node| scope(node) }
                                      .select { |_, nodes| nodes.length > 1 }
                                      .values
                                      .flatten
        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/duplicate_scope.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rails-2.14.2/lib/rubocop/cop/rails/duplicate_scope.rb
rubocop-rails-2.14.2 lib/rubocop/cop/rails/duplicate_scope.rb
rubocop-rails-2.14.1 lib/rubocop/cop/rails/duplicate_scope.rb
rubocop-rails-2.14.0 lib/rubocop/cop/rails/duplicate_scope.rb