Class: Stupidedi::ThreadLocalVar

Inherits:
Object
  • Object
show all
Includes:
Inspect
Defined in:
lib/stupidedi/thread_local.rb

Overview

Examples:

t = ThreadLocalVal("default")
t.get           #=> "default"
t.set("value")  #=> "value"

Thread.new { t.get }.value                  #=> "default"
Thread.new { t.set(:vanish); t.get }.value  #=> :vanish

t.get           #=> "value"

Instance Method Summary collapse

Methods included from Inspect

#inspect

Constructor Details

#initialize(value) ⇒ ThreadLocalVar

Returns a new instance of ThreadLocalVar.



17
18
19
20
21
# File 'lib/stupidedi/thread_local.rb', line 17

def initialize(value)
  @value   = value
  @threads = Hash.new
  @cleaner = lambda {|key| @threads.delete(key) }
end

Instance Method Details

#getObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/stupidedi/thread_local.rb', line 23

def get
  @threads.fetch(key) do
    case @value
    when Numeric, Symbol, nil
      # These are immutable values and can't be cloned
      @value
    else
      finalizer(Thread.current)
      @threads[key] = @value.clone
    end
  end
end

#set(value) ⇒ Object

Returns value.

Returns:

  • value



37
38
39
40
41
42
43
# File 'lib/stupidedi/thread_local.rb', line 37

def set(value)
  unless @threads.include?(key)
    finalizer(Thread.current)
  end

  @threads[key] = value
end

#set?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/stupidedi/thread_local.rb', line 49

def set?
  @threads.include?(key)
end

#unsetObject



45
46
47
# File 'lib/stupidedi/thread_local.rb', line 45

def unset
  @threads.delete(key)
end