Class: Aruba::EventBus

Inherits:
Object
  • Object
show all
Defined in:
lib/aruba/event_bus.rb,
lib/aruba/event_bus/name_resolver.rb

Overview

EventBus

Defined Under Namespace

Classes: NameResolver

Instance Method Summary collapse

Constructor Details

#initialize(resolver) ⇒ EventBus

Create EventBus

Parameters:

  • resolver (#transform)

    A resolver which transforms Symbol, String, Class into an event Class.


15
16
17
18
# File 'lib/aruba/event_bus.rb', line 15

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

Instance Method Details

#notify(event) ⇒ Object

Broadcast an event

Parameters:

  • event (Object)

    An object of registered event class. This object is passed to the event handler.


53
54
55
56
57
# File 'lib/aruba/event_bus.rb', line 53

def notify(event)
  fail NoEventError, 'Please pass an event object, not a class' if event.is_a?(Class)

  @handlers[event.class.to_s].each { |handler| handler.call(event) }
end

#register(event_ids, handler_object = nil) { ... } ⇒ Object

Register for an event

Parameters:

  • event_ids (String, Symbol, Class, Array)

    If Array, register multiple events witht the same handler. If String, Symbol, Class register handler for given event.

  • handler_object (#call) (defaults to: nil)

    The handler object, needs to have method `#call`. Either `handler_object` or `block` can be defined. The handler object gets the event passed to `#call`.

Yields:

  • Handler block which gets the event passed as parameter.


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/aruba/event_bus.rb', line 33

def register(event_ids, handler_object = nil, &handler_proc)
  handler = handler_proc || handler_object

  fail ArgumentError, 'Please pass either an object#call or a handler block' if handler.nil? || !handler.respond_to?(:call)

  Array(event_ids).flatten.each do |id|
    @handlers[
      @resolver.transform(id).to_s
    ] << handler
  end

  nil
end