Class: Twterm::EventDispatcher

Inherits:
Object
  • Object
show all
Includes:
Singleton, Utils
Defined in:
lib/twterm/event_dispatcher.rb

Defined Under Namespace

Classes: Subscription

Instance Method Summary collapse

Methods included from Utils

check_type

Constructor Details

#initializeEventDispatcher

Returns a new instance of EventDispatcher.



9
10
11
# File 'lib/twterm/event_dispatcher.rb', line 9

def initialize
  @subscriptions = []
end

Instance Method Details

#dispatch(event) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/twterm/event_dispatcher.rb', line 13

def dispatch(event)
  @subscriptions
    .select { |s| event.is_a?(s.event) }
    .map(&:callback)
    .each { |cb| cb.call(event) }

  self
end

#register_subscription(subscriber_id, event, callback) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/twterm/event_dispatcher.rb', line 22

def register_subscription(subscriber_id, event, callback)
  check_type Class, event
  unless event <= Event::AbstractEvent
    raise TypeError, 'the second argument must be a subclass of Twterm::Event::AbstractEvent'
  end

  @subscriptions << Subscription.new(subscriber_id, event, callback)

  self
end

#unregister_subscription(subscriber_id, event) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/twterm/event_dispatcher.rb', line 33

def unregister_subscription(subscriber_id, event)
  cond = if event.nil? # remove all subscriptions from the subscriber
           -> s { s.subscriber_id == subscriber_id }
         else          # remove only specified event
           -> s { s.subscriber_id == subscriber_id && s.event == event }
         end

  @subscriptions.reject!(&cond)

  self
end