Skip to content

Instantly share code, notes, and snippets.

@salimhb
Last active April 4, 2025 07:12
Show Gist options
  • Save salimhb/2ff8297b473ce1ad8844a904ed14dfaa to your computer and use it in GitHub Desktop.
Save salimhb/2ff8297b473ce1ad8844a904ed14dfaa to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Place this file under `lib/rubocop/cop/rails/unscoped.rb`
# and add it to `.rubocop.yml`
# ```
# require:
# - ./lib/rubocop/cop/rails/unscoped.rb
# ```
# This file should be excluded from the autoload_lib configuration in config/application.rb
# config.autoload_lib(ignore: %w[... rubocop])
module RuboCop
module Cop
module Rails
# Checks for calls to unscoped from a non model class.
#
# @example
#
# # bad
# Organization.some_scope.unscoped
#
# # good
# Organization.unscoped.some_scope
#
# # good
# Organization.unscoped do
# Organization.some_scope
# end
#
class Unscoped < Base
MSG = 'Use `unscoped` only on model classes. When chaining scopes, `unscoped` clears all previous scopes.'
# match chained calls to unscoped to a non model class
def_node_matcher :unscoped?, <<~PATTERN
(send $(...) :unscoped)
PATTERN
def on_send(node)
return unless unscoped?(node)
receiver = node.receiver
return if receiver.nil? || (receiver.is_a?(RuboCop::AST::ConstNode) && receiver.class_name?)
add_offense(node)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment