Class: Stupidedi::ThreadLocalHash
Overview
Instance Method Summary
collapse
Methods included from Inspect
#inspect
Constructor Details
Returns a new instance of ThreadLocalHash.
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
# File 'lib/stupidedi/thread_local.rb', line 92
def initialize(defaults = {})
@defaults = defaults.clone
@threads = Hash.new
@cleaner = lambda {|key| @threads.delete_if{|(t,_),_| t == key }}
defaults.keys.each do |name|
case defaults[name]
when Numeric, Symbol, nil
instance_eval <<-RUBY
def #{name}
@threads.fetch([key, :#{name}]) do
@defaults[:#{name}]
end
end
RUBY
else
instance_eval <<-RUBY
def #{name}
@threads.fetch([key, :#{name}]) do
finalizer(Thread.current)
@threads[[key, :#{name}]] =
@defaults[:#{name}].clone
end
end
RUBY
end
instance_eval <<-RUBY
def #{name}=(value)
unless @threads.include?(key)
finalizer(Thread.current)
end
@threads[[key, :#{name}]] = value
end
RUBY
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, value = (getter = true)) ⇒ Object
164
165
166
167
168
169
170
171
172
173
174
|
# File 'lib/stupidedi/thread_local.rb', line 164
def method_missing(name, value = (getter = true))
if getter
self[name]
else
if name.to_s =~ /^(.+)=$/
self[$1.to_sym] = value
else
super
end
end
end
|
Instance Method Details
132
133
134
135
136
137
138
139
140
141
142
143
|
# File 'lib/stupidedi/thread_local.rb', line 132
def [](name)
@threads.fetch([Thread.current, name]) do
case value = @defaults[name]
when Numeric, Symbol, nil
value
else
finalizer(Thread.current)
@threads[[key, name]] = value.clone
end
end
end
|
#[]=(name, value) ⇒ Object
145
146
147
148
149
150
151
|
# File 'lib/stupidedi/thread_local.rb', line 145
def []=(name, value)
unless @threads.include?(key)
finalizer(Thread.current)
end
@threads[[key, name]] = value
end
|