在这段代码中,Thread.current的作用是什么?我正在查看在Rails应用程序中使用DCI的这示例。在lib/context.rb中,有以下内容:
module Context
include ContextAccessor
def context=(ctx)
Thread.current[:context] = ctx
end
def in_context
old_context = self.context
self.context = self
res = yield
self.context = old_context
res
end
end用于app/上下文中的各种上下文中,例如:
def bid
in_context do
validator.validate
biddable.create_bid
end
#...
end在in_context块中运行代码并在当前线程上设置键值对有什么好处?
发布于 2015-09-02 08:21:23
通常,在块内部,您无法访问调用者的上下文(除了闭包变量)。
▶ class A
▷ attr_accessor :a
▷ def test
▷ yield if block_given?
▷ end
▷ end
#⇒ :test
▶ inst = A.new
#⇒ #<A:0x00000006f41e28>
▶ inst.a = 'Test'
#⇒ "Test"
▶ inst.test do
▷ puts self
▷ # here you do not have an access to inst at all
▷ # this would raise an exception: puts self.a
▷ end
#⇒ main但是,对于上下文,您仍然可以从内部块访问inst:
▶ in_context do
▷ puts self.context.a
▷ end
#⇒ 'Test'因此,可以介绍proc (考虑A和B都包括Context ):
▶ pr = ->() { puts self.context }
▶ A.new.in_context &pr
#⇒ #<A:0x00000006f41e28>
▶ B.new.in_context &pr
#⇒ #<B:0x00000006f41eff>现在,外部proc pr几乎完全可以访问其调用方。
发布于 2015-09-02 08:24:17
需要Thread.current来支持多线程应用程序,其中每个线程都有自己的上下文。
还包括模块,其中包含上下文。把它们放在一起只会给出更清晰的画面:
# context.rb
def context=(ctx)
Thread.current[:context] = ctx
end
# context_accessor.rb
def context
Thread.current[:context]
endin_context方法的设计是为了安全地更改其块内的上下文。无论更改是什么,当块结束执行时,旧的上下文都会被恢复。
https://stackoverflow.com/questions/32347078
复制相似问题