class Context::Context

Public Class Methods

new(default_value: nil, key: SecureRandom.hex) click to toggle source
# File lib/context/context.rb, line 5
def initialize default_value: nil, key: SecureRandom.hex
  @default_value, @key = default_value, key
end

Public Instance Methods

get() click to toggle source
# File lib/context/context.rb, line 30
def get
  if thread = thread_with_value_or_nil
    thread[@key]
  else
    @default_value
  end
end
method_missing(method, *args) click to toggle source
# File lib/context/context.rb, line 9
def method_missing(method, *args)
  get.send(method, *args)
end
set(value) click to toggle source
# File lib/context/context.rb, line 13
def set value
  Thread.current[@key] = value
end
thread_with_value_or_nil() click to toggle source
# File lib/context/context.rb, line 38
def thread_with_value_or_nil
  thread = Thread.current
  
  while not thread.key?(@key) and thread.parent
    thread = thread.parent
  end
  
  thread.key?(@key) ? thread : nil
end
with(value) { || ... } click to toggle source
# File lib/context/context.rb, line 17
def with value, &block
  thread = Thread.current
  prev_value = thread[@key]

  begin
    thread[@key] = value

    yield
  ensure
    thread[@key] = prev_value
  end
end