6
6
#
7
7
# So the values are scoped within the Thread.current space under the class name
8
8
# of the module.
9
+ #
10
+ # Note that it can also be scoped per-fiber if Rails.application.config.active_support.isolation_level
11
+ # is set to `:fiber`
9
12
class Module
10
13
# Defines a per-thread class attribute and creates class and instance reader methods.
11
14
# The underlying per-thread class variable is set to +nil+, if it is not previously defined.
@@ -14,9 +17,9 @@ class Module
14
17
# thread_mattr_reader :user
15
18
# end
16
19
#
17
- # Current.user # => nil
18
- # Thread.current[:attr_Current_user] = "DHH"
20
+ # Current.user = "DHH"
19
21
# Current.user # => "DHH"
22
+ # Thread.new { Current.user }.values # => nil
20
23
#
21
24
# The attribute name must be a valid method name in Ruby.
22
25
#
@@ -41,7 +44,8 @@ def thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, d
41
44
# to work with inheritance via polymorphism.
42
45
class_eval ( <<-EOS , __FILE__ , __LINE__ + 1 )
43
46
def self.#{ sym }
44
- Thread.current["attr_" + name + "_#{ sym } "]
47
+ @__thread_mattr_#{ sym } ||= "attr_\# {name}_#{ sym } "
48
+ ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{ sym } ]
45
49
end
46
50
EOS
47
51
@@ -53,7 +57,7 @@ def #{sym}
53
57
EOS
54
58
end
55
59
56
- Thread . current [ "attr_" + name + " _#{ sym } "] = default unless default . nil?
60
+ :: ActiveSupport :: IsolatedExecutionState [ "attr_#{ name } _#{ sym } " ] = default unless default . nil?
57
61
end
58
62
end
59
63
alias :thread_cattr_reader :thread_mattr_reader
@@ -84,7 +88,8 @@ def thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true, d
84
88
# to work with inheritance via polymorphism.
85
89
class_eval ( <<-EOS , __FILE__ , __LINE__ + 1 )
86
90
def self.#{ sym } =(obj)
87
- Thread.current["attr_" + name + "_#{ sym } "] = obj
91
+ @__thread_mattr_#{ sym } ||= "attr_\# {name}_#{ sym } "
92
+ ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{ sym } ] = obj
88
93
end
89
94
EOS
90
95
0 commit comments