美文网首页
ActiveSupport::PerThreadRegistry

ActiveSupport::PerThreadRegistry

作者: will2yang | 来源:发表于2019-11-09 00:06 被阅读0次
# 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

      本文链接:https://www.haomeiwen.com/subject/chhgbctx.html