Class: Stupidedi::ThreadLocalHash
- Inherits:
-
Object
- Object
- Stupidedi::ThreadLocalHash
show all
- Includes:
- Inspect
- Defined in:
- lib/stupidedi/thread_local.rb
Overview
Instance Method Summary
collapse
Methods included from Inspect
#inspect
Constructor Details
Returns a new instance of ThreadLocalHash.
90
91
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
|
# File 'lib/stupidedi/thread_local.rb', line 90
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 " def \#{name}\n @threads.fetch([key, :\#{name}]) do\n @defaults[:\#{name}]\n end\n end\n RUBY\n else\n instance_eval <<-RUBY\n def \#{name}\n @threads.fetch([key, :\#{name}]) do\n finalizer(Thread.current)\n @threads[[key, :\#{name}]] =\n @defaults[:\#{name}].clone\n end\n end\n RUBY\n end\n\n instance_eval <<-RUBY\n def \#{name}=(value)\n unless @threads.include?(key)\n finalizer(Thread.current)\n end\n\n @threads[[key, :\#{name}]] = value\n end\n RUBY\n end\nend\n"
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, value = (getter = true)) ⇒ Object
162
163
164
165
166
167
168
169
170
171
172
|
# File 'lib/stupidedi/thread_local.rb', line 162
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
#[](name) ⇒ Object
130
131
132
133
134
135
136
137
138
139
140
141
|
# File 'lib/stupidedi/thread_local.rb', line 130
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
143
144
145
146
147
148
149
|
# File 'lib/stupidedi/thread_local.rb', line 143
def []=(name, value)
unless @threads.include?(key)
finalizer(Thread.current)
end
@threads[[key, name]] = value
end
|