Class: Brute::Hooks::Registry

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



81
82
83
# File 'lib/brute/hooks.rb', line 81

def initialize
  @subscribers = Hash.new { |hash, key| hash[key] = [] }
end

Instance Method Details

#any?(event) ⇒ Boolean

Returns:

  • (Boolean)


122
# File 'lib/brute/hooks.rb', line 122

def any?(event) = @subscribers[event.to_sym].any?

#emit(event, env, *extras, &block) ⇒ Object

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(MIDDLEWARE_DURATION_EVENT, env, self) { result = @app.call(env) }
# => .on(MIDDLEWARE_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.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/brute/hooks.rb', line 100

def emit(event, env, *extras, &block)
  if block
    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
  else
    @subscribers[event.to_sym].each { |subscriber| subscriber.call(env, *extras) }
  end

  nil
end

#on(event, &block) ⇒ Object



85
86
87
88
# File 'lib/brute/hooks.rb', line 85

def on(event, &block)
  @subscribers[event.to_sym] << block
  self
end