此代码中的Thread.current
是什么?我正在查看在{Rails}应用程序中使用DCI的this示例。在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 / contexts中的各种上下文,例如:
def bid
in_context do
validator.validate
biddable.create_bid
end
#...
end
在in_context
块中运行代码并在当前线程上设置键值对有什么好处?
答案 0 :(得分:3)
通常,在内部块中,您无法访问调用者的上下文(除了闭包变量。)
▶ 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
几乎可以完全访问其来电者。
答案 1 :(得分:2)
Thread.current
来支持多线程应用程序,其中每个线程都有自己的上下文。
还包含ContextAccessor
module,其中一个获取上下文。将它们放在一起只会给出更清晰的图像:
# context.rb
def context=(ctx)
Thread.current[:context] = ctx
end
# context_accessor.rb
def context
Thread.current[:context]
end
in_context
方法旨在安全地更改其块内的上下文。无论更改是什么,当块结束执行时,旧的上下文都会恢复。