Class: Chronos::Adapters::ThreadLocalContextStore

Inherits:
Object
  • Object
show all
Defined in:
lib/chronos/adapters/thread_local_context_store.rb

Overview

Stores execution context in the current Ruby thread.

Examples:

store.with_context(:request_id => "r1") { store.get }

Instance Method Summary collapse

Constructor Details

#initializeThreadLocalContextStore

Returns a new instance of ThreadLocalContextStore.



16
17
18
# File 'lib/chronos/adapters/thread_local_context_store.rb', line 16

def initialize
  @key = "chronos_context_#{object_id}".freeze
end

Instance Method Details

#clearObject



30
31
32
33
# File 'lib/chronos/adapters/thread_local_context_store.rb', line 30

def clear
  Thread.current[@key] = nil
  nil
end

#getObject



20
21
22
# File 'lib/chronos/adapters/thread_local_context_store.rb', line 20

def get
  Thread.current[@key] || {}
end

#set(context) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
# File 'lib/chronos/adapters/thread_local_context_store.rb', line 24

def set(context)
  raise ArgumentError, "context must be a Hash" unless context.is_a?(Hash)

  Thread.current[@key] = context
end

#with_context(context) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/chronos/adapters/thread_local_context_store.rb', line 35

def with_context(context)
  previous = Thread.current[@key]
  set(merge_context(previous || {}, context))
  yield
ensure
  previous ? Thread.current[@key] = previous : clear
end