Class: Brute::Hooks::Registry
- Inherits:
-
Object
- Object
- Brute::Hooks::Registry
- Defined in:
- lib/brute/hooks.rb
Overview
The pub/sub registry a pipeline owns; use and run bind an emit to it.
Instance Method Summary collapse
- #any?(event) ⇒ Boolean
-
#emit(event, env, *extras, &block) ⇒ Object
Fire an event.
-
#initialize ⇒ Registry
constructor
A new instance of Registry.
- #on(event, &block) ⇒ Object
Constructor Details
#initialize ⇒ Registry
Returns a new instance of Registry.
96 97 98 |
# File 'lib/brute/hooks.rb', line 96 def initialize @subscribers = Hash.new { |hash, key| hash[key] = [] } end |
Instance Method Details
#any?(event) ⇒ Boolean
144 |
# File 'lib/brute/hooks.rb', line 144 def any?(event) = @subscribers[event.to_sym].any? |
#emit(event, env, *extras, &block) ⇒ Object
Fire an event. An emitter announces; it answers nothing, and what a subscriber's block happens to evaluate to is not a signal. A layer that wants to take part in a turn does it by mutating what it was handed, never by returning something.
Given a block, the event is timed instead: the block is the work, and
subscribers fire once it is done, called as
|env, started, finished, *extras| rather than |env, *extras|.
Both stamps are monotonic, so a clock adjustment mid-turn cannot
produce a negative duration.
The block is the work and nothing more: emit answers nothing in
either form, so a caller that needs the work's value takes it inside
the block.
result = nil
emit(DURATION_EVENT, env, self) { result = @app.call(env) }
# => .on(DURATION_EVENT) { |env, started, finished, layer| ... }
Subscribers fire from an ensure, so work that raises is still timed and still reported before the exception carries on up.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/brute/hooks.rb', line 126 def emit(event, env, *extras, &block) unless block @subscribers[event.to_sym].each { |subscriber| subscriber.call(env, *extras) } return nil end started = Process.clock_gettime(Process::CLOCK_MONOTONIC) begin block.call ensure finished = Process.clock_gettime(Process::CLOCK_MONOTONIC) @subscribers[event.to_sym].each { |subscriber| subscriber.call(env, started, finished, *extras) } end nil end |
#on(event, &block) ⇒ Object
100 101 102 103 |
# File 'lib/brute/hooks.rb', line 100 def on(event, &block) @subscribers[event.to_sym] << block self end |