The Ruby Thread # [] =
method allows you to keep a unique value for each thread. (It's like ThreadLocal
in Java)
If you use this, the application server (almost all AP servers such as Passenger) associated with 1 thread and 1 request will
It can be used as a thread-local variable that can be closed and used only during one request.
You can define a thread-local variable foo
by assigningThread.current [: foo]
to the current thread as follows:
def self.foo
Thread.current[:foo] ||= 0
end
There is also a gem called RecordWithOperator that provides the Ruby on Rails framework with the ability to record record operators (creators, updaters, deleters).
It is implemented using this Thread # [] =
.
https://github.com/nay/record_with_operator/blob/4389d077b0303b956cc211ef439a46a216ae2cc0/lib/record_with_operator/operator.rb#L4
If you are using an application server such as Passenger or Puma that reuses threads once created Since the thread local variable is associated with the thread that is supposed to be reused, it must be explicitly destroyed on the application side. Please note that the variable defined in the previous request (thread) can be referenced in another request.
Redmine also previously had code to handle the current user using Thread # [] =
There was a case of a security bug in which the name of another user was displayed in the error message.
http://www.redmine.org/issues/16685
This can be avoided by explicitly discarding the Thread.current value on the application side.
If you use a gem called RequestStore, you can use the Rack :: Middleware layer for each request.
It will now clear the value of Thread.current
.
An example of use is as follows:
def self.foo
RequestStore.store[:foo] ||= 0
end
Recommended Posts