Class: Class

Inherits:
Object
  • Object
show all
Defined in:
lib/thread_local_accessor.rb

Overview

Instance Method Summary collapse

Instance Method Details

#thread_local_accessor(name, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/thread_local_accessor.rb', line 5

def thread_local_accessor name, options = {}
  m = Module.new do
    define_method "#{name}=" do |value|
      k = (Class === self ? self : self.class).object_id.to_s + "_" + name.to_s
      Thread.current[k] = value
    end

    define_method name do
      k = (Class === self ? self : self.class).object_id.to_s + "_" + name.to_s
      if Thread.current.key?(k)
        Thread.current[k]
      else
        options[:default]
      end
    end
  end
 
  class_eval do
    include m
    extend m
  end
end