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.


20
21
22
23
24
# File 'lib/stupidedi/thread_local.rb', line 20

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

Instance Method Details

#get


26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/stupidedi/thread_local.rb', line 26

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)

Returns value.

Returns:

  • value


40
41
42
43
44
45
46
# File 'lib/stupidedi/thread_local.rb', line 40

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

  @threads[key] = value
end

#set?Boolean

Returns:

  • (Boolean)

52
53
54
# File 'lib/stupidedi/thread_local.rb', line 52

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

#unset


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

def unset
  @threads.delete(key)
end