ActiveSupport::PerThreadRegistry代码阅读

# frozen_string_literal: true

require "active_support/core_ext/module/delegation"

module ActiveSupport
  module PerThreadRegistry
    def self.extended(object)
      object.instance_variable_set "@per_thread_registry_key", object.name.freeze
    end

    def instance
      Thread.current[@per_thread_registry_key] ||= new
    end

    private
      def method_missing(name, *args, &block)
        # Caches the method definition as a singleton method of the receiver.
        #
        # By letting #delegate handle it, we avoid an enclosure that'll capture args.
        singleton_class.delegate name, to: :instance

        send(name, *args, &block)
      end
  end
end

用于在类里保存当前线程的变量信息,也就是说一个类extend了PerThreadRegistry,那么这个类的变量将只在这个线程里共享。

你可能感兴趣的:(ActiveSupport::PerThreadRegistry代码阅读)