Created
September 28, 2012 16:08
-
-
Save jwaldrip/3800718 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module OauthResource::ThreadLocal | |
def thread_local_accessor(*names) | |
names.each do |name| | |
class_variable_set :"@@#{name}", {} | |
accessor = class_variable_get("@@#{name}") | |
# Thread Accessor Getter | |
define_singleton_method name do | |
thread_id = Thread.current.object_id | |
accessor[thread_id] | |
end | |
# Thread Accessor Setter | |
define_singleton_method "#{name}=" do |val| | |
thread_id = Thread.current.object_id | |
finalizer = ->(id){ class_variable_get("@@#{name}").delete(id) } | |
ObjectSpace.define_finalizer Thread.current, finalizer unless accessor.has_key? thread_id | |
accessor[thread_id] = val | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment