Module: Core::Local

Extended by:
Extension
Defined in:
lib/core/local.rb,
lib/core/local/store.rb,
lib/core/local/version.rb

Overview

public

Manage thread-local program state for an object.

Defined Under Namespace

Classes: Store

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.versionObject



7
8
9
# File 'lib/core/local/version.rb', line 7

def self.version
  VERSION
end

Instance Method Details

#localize(key, value) ⇒ Object

public

Localize value for key in the current thread or fiber.

Be aware that you can easily introduce memory leaks into your program if you aren’t careful to clean up localized state. There’s two ways to approach this:

1. Pass a block to `localize`. The value will be localized and cleaned up after being yielded to the block.

2. Call `unlocalize` manually when you no longer need the localized value.


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/core/local.rb', line 23

def localize(key, value)
  key = localized_key(key)

  Core::Local::Store[key] = value

  if block_given?
    begin
      yield value
    ensure
      Core::Local::Store.delete(key)
    end
  else
    value
  end
end

#localized(key, fallback = nil) ⇒ Object

public

Returns the localized value for key, or fallback.



41
42
43
# File 'lib/core/local.rb', line 41

def localized(key, fallback = nil)
  Core::Local::Store.fetch(localized_key(key), fallback)
end

#unlocalize(key) ⇒ Object

public

Deletes the localized value for key.



47
48
49
# File 'lib/core/local.rb', line 47

def unlocalize(key)
  Core::Local::Store.delete(localized_key(key))
end