Class: Easyop::Events::Bus::ActiveSupportNotifications

Inherits:
Base
  • Object
show all
Defined in:
lib/easyop/events/bus/active_support_notifications.rb

Overview

Bus adapter backed by ActiveSupport::Notifications.

Requires activesupport (not auto-required). Raises LoadError if unavailable.

Examples:

Easyop::Events::Registry.bus = :active_support

# or manually:
bus = Easyop::Events::Bus::ActiveSupportNotifications.new
Easyop::Events::Registry.bus = bus

Instance Method Summary collapse

Instance Method Details

#publish(event) ⇒ Object

Publish event via ActiveSupport::Notifications.instrument. The full event hash (name, payload, metadata, timestamp, source) is passed as the AS notification payload.

Parameters:



22
23
24
25
# File 'lib/easyop/events/bus/active_support_notifications.rb', line 22

def publish(event)
  _ensure_as!
  ::ActiveSupport::Notifications.instrument(event.name, event.to_h)
end

#subscribe(pattern, &block) ⇒ Object

Subscribe to events matching pattern via ActiveSupport::Notifications.subscribe. Glob patterns are converted to Regexp before passing to AS.

Parameters:

  • pattern (String, Regexp)

Returns:

  • (Object)

    AS subscription handle



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/easyop/events/bus/active_support_notifications.rb', line 32

def subscribe(pattern, &block)
  _ensure_as!

  as_pattern = _as_pattern(pattern)

  ::ActiveSupport::Notifications.subscribe(as_pattern) do |*args|
    as_event     = ::ActiveSupport::Notifications::Event.new(*args)
    p            = as_event.payload

    # Reconstruct an Easyop::Events::Event from the AS notification payload.
    easyop_event = Event.new(
      name:      (p[:name] || as_event.name).to_s,
      payload:   p[:payload]  || {},
      metadata:  p[:metadata] || {},
      timestamp: p[:timestamp],
      source:    p[:source]
    )
    block.call(easyop_event)
  end
end

#unsubscribe(handle) ⇒ Object

Unsubscribe using the handle returned by #subscribe.

Parameters:

  • handle (Object)

    AS subscription object



55
56
57
58
# File 'lib/easyop/events/bus/active_support_notifications.rb', line 55

def unsubscribe(handle)
  _ensure_as!
  ::ActiveSupport::Notifications.unsubscribe(handle)
end