Module: Ramaze::ThreadAccessor
- Included in:
- Object
- Defined in:
- lib/ramaze/snippets/ramaze/thread_accessor.rb
Overview
A alike of attr_accessor and friends, but for thread variables in Thread::current
Class Method Summary collapse
-
.each(*names) ⇒ Object
Iterate over the names and yield accordingly.
Instance Method Summary collapse
-
#thread_accessor(*names, &initializer) ⇒ Object
thread_writer and thread_reader, initializer is a block that may be given and its result will be the new value in case the reader was never called before or the value wasn’t set before.
-
#thread_reader(*names, &initializer) ⇒ Object
Reader accessor for Thread::current.
-
#thread_writer(*names) ⇒ Object
Simple writer accessor to Thread::current=.
Class Method Details
.each(*names) ⇒ Object
Iterate over the names and yield accordingly. names are either objects responding to #to_sym or hashes.
It’s only used within this module for abstractin-purposes. Usage below.
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/ramaze/snippets/ramaze/thread_accessor.rb', line 12 def self.each(*names) names.each do |name| if name.respond_to?(:to_hash) name.to_hash.each do |key, meth| key, meth = key.to_sym, meth.to_sym yield key, meth end else key = meth = name.to_sym yield key, meth end end end |
Instance Method Details
#thread_accessor(*names, &initializer) ⇒ Object
thread_writer and thread_reader, initializer is a block that may be given and its result will be the new value in case the reader was never called before or the value wasn’t set before.
29 30 31 32 |
# File 'lib/ramaze/snippets/ramaze/thread_accessor.rb', line 29 def thread_accessor(*names, &initializer) thread_writer(*names) thread_reader(*names, &initializer) end |
#thread_reader(*names, &initializer) ⇒ Object
Reader accessor for Thread::current
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/ramaze/snippets/ramaze/thread_accessor.rb', line 42 def thread_reader(*names, &initializer) ThreadAccessor.each(*names) do |key, meth| if initializer define_method(meth) do unless Thread.current.key?(key) Thread.current[key] = instance_eval(&initializer) else Thread.current[key] end end else define_method(meth){ Thread.current[key] } end end end |
#thread_writer(*names) ⇒ Object
Simple writer accessor to Thread::current=
35 36 37 38 39 |
# File 'lib/ramaze/snippets/ramaze/thread_accessor.rb', line 35 def thread_writer(*names) ThreadAccessor.each(*names) do |key, meth| define_method("#{meth}="){|obj| Thread.current[key] = obj } end end |