2013-04-09 12:04:39 -04:00
|
|
|
module ActiveSupport
|
2013-04-13 02:15:11 -04:00
|
|
|
# This module is used to encapsulate access to thread local variables.
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 11:08:00 -04:00
|
|
|
# Instead of polluting the thread locals namespace:
|
|
|
|
#
|
|
|
|
# Thread.current[:connection_handler]
|
|
|
|
#
|
|
|
|
# you define a class that extends this module:
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 02:15:11 -04:00
|
|
|
# module ActiveRecord
|
|
|
|
# class RuntimeRegistry
|
|
|
|
# extend ActiveSupport::PerThreadRegistry
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 02:15:11 -04:00
|
|
|
# attr_accessor :connection_handler
|
|
|
|
# end
|
|
|
|
# end
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 11:08:00 -04:00
|
|
|
# and invoke the declared instance accessors as class methods. So
|
2013-04-13 02:15:11 -04:00
|
|
|
#
|
2013-04-13 11:08:00 -04:00
|
|
|
# ActiveRecord::RuntimeRegistry.connection_handler = connection_handler
|
2013-04-13 02:15:11 -04:00
|
|
|
#
|
2013-04-13 11:08:00 -04:00
|
|
|
# sets a connection handler local to the current thread, and
|
2013-04-13 02:15:11 -04:00
|
|
|
#
|
|
|
|
# ActiveRecord::RuntimeRegistry.connection_handler
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 11:08:00 -04:00
|
|
|
# returns a connection handler local to the current thread.
|
|
|
|
#
|
|
|
|
# This feature is accomplished by instantiating the class and storing the
|
|
|
|
# instance as a thread local keyed by the class name. In the example above
|
|
|
|
# a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>.
|
|
|
|
# The class methods proxy to said thread local instance.
|
2013-04-09 12:04:39 -04:00
|
|
|
#
|
2013-04-13 02:15:11 -04:00
|
|
|
# If the class has an initializer, it must accept no arguments.
|
2013-04-09 12:04:39 -04:00
|
|
|
module PerThreadRegistry
|
2013-12-12 20:40:21 -05:00
|
|
|
def self.extended(object)
|
|
|
|
object.instance_variable_set '@per_thread_registry_key', object.name.freeze
|
|
|
|
end
|
|
|
|
|
2013-11-06 19:32:47 -05:00
|
|
|
def instance
|
2013-12-12 20:40:21 -05:00
|
|
|
Thread.current[@per_thread_registry_key] ||= new
|
2013-11-06 19:32:47 -05:00
|
|
|
end
|
|
|
|
|
2013-04-09 12:04:39 -04:00
|
|
|
protected
|
2013-04-13 12:56:19 -04:00
|
|
|
def method_missing(name, *args, &block) # :nodoc:
|
2013-04-13 11:08:00 -04:00
|
|
|
# Caches the method definition as a singleton method of the receiver.
|
2013-04-13 13:14:12 -04:00
|
|
|
define_singleton_method(name) do |*a, &b|
|
2013-11-06 19:32:47 -05:00
|
|
|
instance.public_send(name, *a, &b)
|
2013-04-13 11:08:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
send(name, *args, &block)
|
|
|
|
end
|
2013-04-09 12:04:39 -04:00
|
|
|
end
|
|
|
|
end
|