Module: Smith::Events

Defined in:
lib/smith/events.rb,
lib/smith/events/bus.rb,
lib/smith/events/step_failed.rb,
lib/smith/events/subscription.rb,
lib/smith/events/step_completed.rb

Defined Under Namespace

Classes: Scope, StepCompleted, StepFailed, Subscription

Class Method Summary collapse

Class Method Details

.detach(subscription) ⇒ Object

Removes a subscription from the registry. Called by Subscription#cancel; safe to call more than once.



45
46
47
48
49
50
51
52
53
54
# File 'lib/smith/events/bus.rb', line 45

def detach(subscription)
  REGISTRY_MUTEX.synchronize do
    bucket = registry[subscription.event_class]
    next unless bucket

    bucket.delete(subscription)
    registry.delete(subscription.event_class) if bucket.empty?
  end
  nil
end

.emit(event) ⇒ Object



56
57
58
# File 'lib/smith/events/bus.rb', line 56

def emit(event)
  matching_subscriptions(event).each { |sub| dispatch_to(sub, event) }
end

.on(event_class, **opts, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/smith/events/bus.rb', line 33

def on(event_class, **opts, &block)
  sub = Subscription.new(event_class, handler: block, predicate: opts[:if])
  REGISTRY_MUTEX.synchronize do
    @sequence = (@sequence || 0) + 1
    sub.sequence_number = @sequence
    (registry[event_class] ||= []) << sub
  end
  sub
end

.reset!Object



67
68
69
70
71
72
# File 'lib/smith/events/bus.rb', line 67

def reset!
  REGISTRY_MUTEX.synchronize do
    @registry = {}
    @sequence = 0
  end
end

.subscriptionsObject

Registration-ordered snapshot of the live subscriptions. Cancelled subscriptions are detached from the registry, so this reflects only what will actually receive events.



28
29
30
31
# File 'lib/smith/events/bus.rb', line 28

def subscriptions
  snapshot = REGISTRY_MUTEX.synchronize { registry.values.flatten }
  snapshot.sort_by!(&:sequence_number)
end

.withinObject



60
61
62
63
64
65
# File 'lib/smith/events/bus.rb', line 60

def within
  scope = Scope.new
  yield scope
ensure
  scope&.cancel_all
end