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,那么这个类的变量将只在这个线程里共享。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,795评论 1 32
  • 一:java概述:1,JDK:Java Development Kit,java的开发和运行环境,java的开发工...
    ZaneInTheSun阅读 7,577评论 0 11
  • 01 前几天早上醒来就已经是十点钟了,我摸起手机第一件事就是打开了微信朋友圈,一眼望去,全是有关周杰伦生日有关周杰...
    葡萄RRRan阅读 3,188评论 0 0
  • —最好的礼物— 今天早上,刚进教室坐下来改作业没多久,就收到了来自曹轩宇的一份心意——...
    藤藤_阅读 8,242评论 1 1
  • (日更第16天) 昨天看了一篇短文,是关于“自我界限”的,文中有句话的意思是皮肤之外的东西都不属于自己。这句话刷新...
    花枝笑阅读 1,222评论 2 4