Assume less in the on_unload callback for AR scopes

Please check the comment in the patch for details.

Thanks to @casperisfine for suggesting this refactor.
This commit is contained in:
Xavier Noria 2022-03-21 11:51:03 +01:00
parent 2797fc413a
commit b764fc24c8
2 changed files with 22 additions and 1 deletions

View File

@ -394,7 +394,11 @@ To keep using the current cache store, you can turn off cache versioning entirel
config.after_initialize do
unless app.config.cache_classes
Rails.autoloaders.main.on_unload do |_cpath, value, _abspath|
value.current_scope = nil if value.is_a?(Class) && value < ActiveRecord::Base
# Conditions are written this way to be robust against custom
# implementations of value#is_a? or value#<.
if Class === value && ActiveRecord::Base > value
value.current_scope = nil
end
end
end
end

View File

@ -342,8 +342,25 @@ module ApplicationTests
test "Current scopes in AR models are reset on reloading" do
rails %w(generate model post)
rails %w(db:migrate)
app_file "app/models/a.rb", "A = 1"
app_file "app/models/m.rb", "module M; end"
app_file "app/models/post.rb", <<~RUBY
class Post < ActiveRecord::Base
def self.is_a?(_)
false
end
def self.<(_)
false
end
end
RUBY
require "#{app_path}/config/environment"
A
M
Post.current_scope = Post
assert_not_nil ActiveRecord::Scoping::ScopeRegistry.current_scope(Post) # precondition