Class: Spree::Events::Adapters::ActiveSupportNotifications

Inherits:
Base
  • Object
show all
Defined in:
lib/spree/events/adapters/active_support_notifications.rb

Overview

Adapter for ActiveSupport::Notifications backend.

This adapter wraps Rails’ built-in notification system to provide the Spree event infrastructure. It can be swapped out for other implementations (e.g., Redis pub/sub, Kafka) without changing the subscriber API.

Examples:

Publishing an event

adapter = ActiveSupportNotifications.new(registry)
adapter.publish('order.complete', { id: 1 })

Constant Summary collapse

NAMESPACE =
'spree'

Instance Attribute Summary

Attributes inherited from Base

#registry

Instance Method Summary collapse

Constructor Details

#initialize(registry) ⇒ ActiveSupportNotifications



20
21
22
23
24
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 20

def initialize(registry)
  super
  @as_subscription = nil
  @mutex = Mutex.new
end

Instance Method Details

#activate!Object

Activate all registered subscriptions

This is called during Rails initialization to set up the single AS::N subscription that catches all Spree events.



72
73
74
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 72

def activate!
  ensure_as_subscription
end

#deactivate!Object

Deactivate all AS::N subscriptions



77
78
79
80
81
82
83
84
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 77

def deactivate!
  @mutex.synchronize do
    if @as_subscription
      ::ActiveSupport::Notifications.unsubscribe(@as_subscription)
      @as_subscription = nil
    end
  end
end

#publish(event_name, payload, metadata = {}) ⇒ Spree::Event

Publish an event to all matching subscribers



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 32

def publish(event_name, payload,  = {})
  event = build_event(event_name, payload, )
  instrument_name = namespaced_event(event_name)

  ::ActiveSupport::Notifications.instrument(instrument_name, event: event) do
    # The block is intentionally empty - we use the instrument
    # to trigger subscribers, not to wrap code execution
  end

  event
end

#subscribe(pattern, subscriber, options = {}) ⇒ Object

Subscribe to an event pattern

This method registers a subscriber in the registry. The actual AS::N subscription is created once via activate!



52
53
54
55
56
57
58
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 52

def subscribe(pattern, subscriber, options = {})
  # Register in our registry
  registry.register(pattern, subscriber, options)

  # Ensure the global AS::N subscription exists
  ensure_as_subscription
end

#unsubscribe(pattern, subscriber) ⇒ Object

Unsubscribe from an event pattern



64
65
66
# File 'lib/spree/events/adapters/active_support_notifications.rb', line 64

def unsubscribe(pattern, subscriber)
  registry.unregister(pattern, subscriber)
end