Class: Cabin::Context
- Inherits:
-
Object
- Object
- Cabin::Context
- Defined in:
- lib/cabin/context.rb
Overview
Logging context exists to make it easy to add and later undo any changes made to the context data associated with a given Logging::Channel
Usage:
context = channel.context
context["foo"] = "Hello world!"
channel.info("Sample log") # output includes { "foo" => "Hello world!" }
context.clear
channel.info("Sample log 2") # context cleared, key "foo" removed.
Essentially, a Cabin::Context acts as a transactional proxy on top of a Cabin::Channel. Any changes you make in a context are passed through to the channel while keeping an ordered record of the changes made so you can unroll those changes when the context is no longer needed..
Instance Method Summary collapse
-
#[](key) ⇒ Object
def []=.
-
#[]=(key, value) ⇒ Object
def on_clear.
-
#clear ⇒ Object
Undo any changes made to the channel by this context.
-
#initialize(channel) ⇒ Context
constructor
A new instance of Context.
-
#on_clear(&block) ⇒ Object
def initialize.
Constructor Details
#initialize(channel) ⇒ Context
Returns a new instance of Context.
20 21 22 23 |
# File 'lib/cabin/context.rb', line 20 def initialize(channel) @changes = [] @channel = channel end |
Instance Method Details
#[](key) ⇒ Object
def []=
36 37 38 |
# File 'lib/cabin/context.rb', line 36 def [](key) @channel[key] end |
#[]=(key, value) ⇒ Object
def on_clear
29 30 31 32 33 34 |
# File 'lib/cabin/context.rb', line 29 def []=(key, value) # Maintain a record of what was changed so clear() can undo this context. # This record is in reverse order so it can be undone in reverse later. @changes.unshift([key, value, @channel[key]]) @channel[key] = value end |
#clear ⇒ Object
Undo any changes made to the channel by this context.
41 42 43 44 45 46 47 48 49 |
# File 'lib/cabin/context.rb', line 41 def clear @changes.each do |key, value, original| if original.nil? @channel.remove(key) else @channel[key] = original end end end |
#on_clear(&block) ⇒ Object
def initialize
25 26 27 |
# File 'lib/cabin/context.rb', line 25 def on_clear(&block) @clear_callback = block end |