Class: Switest::Events

Inherits:
Object
  • Object
show all
Defined in:
lib/switest/events.rb

Overview

Lightweight one-shot event emitter with guard support for conditional event handling. Supports hash equality, regex, array membership, and proc guards.

Used for routing inbound call offers from Client to Agent.listen_for_call.

Instance Method Summary collapse

Constructor Details

#initializeEvents

Returns a new instance of Events.



10
11
12
# File 'lib/switest/events.rb', line 10

def initialize
  @handlers = Hash.new { |h, k| h[k] = [] }
end

Instance Method Details

#emit(event, data = {}) ⇒ Object

Emit an event, triggering and removing all matching handlers



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/switest/events.rb', line 20

def emit(event, data = {})
  matched = []
  remaining = []

  @handlers[event].each do |handler|
    if guards_match?(handler[:guards], data)
      matched << handler
    else
      remaining << handler
    end
  end

  @handlers[event] = remaining
  matched.each { |handler| handler[:callback].call(data) }
end

#once(event, guards = {}, &block) ⇒ Object

Register a one-time event handler with optional guards



15
16
17
# File 'lib/switest/events.rb', line 15

def once(event, guards = {}, &block)
  @handlers[event] << { guards: guards, callback: block }
end