Class: Failbot::ThreadLocalVariable

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

Overview

Public: A simplified implementation of [‘::Concurrent::ThreadLocalVar`](github.com/ruby-concurrency/concurrent-ruby/blob/7dc6eb04142f008ffa79a59c125669c6fcbb85a8/lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb)

Why not just use ‘concurrent-ruby`? We wanted to minimize external dependencies to avoid conflicts with gems already installed with `github/github`.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ ThreadLocalVariable

Returns a new instance of ThreadLocalVariable.



7
8
9
10
# File 'lib/failbot/thread_local_variable.rb', line 7

def initialize(&block)
  @default_block = block || proc {}
  @key = "_thread_local_variable_#{object_id}".to_sym
end

Instance Method Details

#valueObject



12
13
14
# File 'lib/failbot/thread_local_variable.rb', line 12

def value
  value_from_thread(Thread.current)
end

#value=(val) ⇒ Object



16
17
18
# File 'lib/failbot/thread_local_variable.rb', line 16

def value=(val)
  Thread.current.thread_variable_set(@key, val)
end

#value_from_thread(thread) ⇒ Object



20
21
22
23
24
25
# File 'lib/failbot/thread_local_variable.rb', line 20

def value_from_thread(thread)
  if !thread.thread_variables.include?(@key)
    thread.thread_variable_set(@key, @default_block.call)
  end
  thread.thread_variable_get(@key)
end