Module: Tins::ThreadGlobal
- Included in:
- Object
- Defined in:
- lib/tins/dslkit.rb
Instance Method Summary collapse
-
#instance_thread_global(name, value = nil) ⇒ Object
Define a thread global variable for the current instance with name name.
-
#thread_global(name, default_value = nil, &default) ⇒ Object
Define a thread global variable named name in this module/class.
Instance Method Details
#instance_thread_global(name, value = nil) ⇒ Object
Define a thread global variable for the current instance with name name. If the value value is given, it is used to initialize the variable.
89 90 91 92 93 94 95 96 |
# File 'lib/tins/dslkit.rb', line 89 def instance_thread_global(name, value = nil) sc = class << self extend Tins::ThreadGlobal self end sc.thread_global name, value self end |
#thread_global(name, default_value = nil, &default) ⇒ Object
Define a thread global variable named name in this module/class. If the value value is given, it is used to initialize the variable.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/tins/dslkit.rb', line 54 def thread_global(name, default_value = nil, &default) is_a?(Module) or raise TypeError, "receiver has to be a Module" default_value && default and raise ArgumentError, "require either default_falue or default block" if default_value default = -> * { default_value } end name = name.to_s var_name = "@__#{name}_#{__id__.abs}__" lock = Mutex.new modul = self define_method(name) do lock.synchronize { if default && !modul.instance_variable_defined?(var_name) modul.instance_variable_set var_name, default.call end modul.instance_variable_get var_name } end define_method(name + "=") do |value| lock.synchronize { modul.instance_variable_set var_name, value } end self end |