Class: Chronos::Adapters::FiberLocalContextStore

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

Overview

Stores execution context on the current Fiber when Ruby exposes Fiber storage.

Examples:

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

Instance Method Summary collapse

Constructor Details

#initialize(fallback = ThreadLocalContextStore.new) ⇒ FiberLocalContextStore

Returns a new instance of FiberLocalContextStore.



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

def initialize(fallback = ThreadLocalContextStore.new)
  @key = "chronos_context_#{object_id}".to_sym
  @fallback = fallback
end

Instance Method Details

#clearObject



31
32
33
34
# File 'lib/chronos/adapters/fiber_local_context_store.rb', line 31

def clear
  supported? ? Fiber[@key] = nil : @fallback.clear
  nil
end

#getObject



21
22
23
# File 'lib/chronos/adapters/fiber_local_context_store.rb', line 21

def get
  supported? ? (Fiber[@key] || {}) : @fallback.get
end

#set(context) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
# File 'lib/chronos/adapters/fiber_local_context_store.rb', line 25

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

  supported? ? Fiber[@key] = context : @fallback.set(context)
end

#with_context(context) ⇒ Object



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

def with_context(context)
  previous = get
  set(previous.merge(valid_context(context)))
  yield
ensure
  previous && !previous.empty? ? set(previous) : clear
end