Class: EventBus

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

Defined Under Namespace

Classes: Registrations

Class Method Summary collapse

Class Method Details

.clearObject

Delete all current listener registrations

Returns:

  • the EventBus, ready to be called again.



52
53
54
55
# File 'lib/event_bus.rb', line 52

def clear
  registrations.clear
  self
end

.publish(event_name, details = {}) ⇒ Object Also known as: announce, broadcast

Announce an event to any waiting listeners.

The event_name is added to the details hash (with the key :event_name) before the event is passed on to listeners.

Parameters:

  • event_name (String, Symbol)

    the name of your event

  • details (Hash) (defaults to: {})

    the information you want to pass to the listeners

Returns:

  • the EventBus, ready to be called again.



17
18
19
20
# File 'lib/event_bus.rb', line 17

def publish(event_name, details = {})
  registrations.announce(event_name, details)
  self
end

.register(listener) ⇒ Object

(experimental)



60
61
62
63
64
65
# File 'lib/event_bus.rb', line 60

def register(listener)
  listener.events_map.each do |pattern, method_name|
    registrations.add(pattern, listener, method_name)
  end
  self
end

.subscribe(pattern, listener = nil, method_name = nil, &blk) ⇒ Object Also known as: listen_for

Register a single listener.

Parameters:

  • pattern (String, Regex)

    listen for any events whose name matches this pattern

  • listener (defaults to: nil)

    the object to be notified when a matching event occurs

  • method_name (Symbol) (defaults to: nil)

    the method to be called on listener when a matching event occurs

Returns:

  • the EventBus, ready to be called again.



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

def subscribe(pattern, listener = nil, method_name = nil, &blk)
  if listener
    raise ArgumentError.new('You cannot give both a listener and a block') if block_given?
    raise ArgumentError.new('You must supply a method name') unless method_name
    registrations.add_method(pattern, listener, method_name)
  else
    raise ArgumentError.new('You must provide a listener or a block') unless block_given?
    registrations.add_block(pattern, blk)
  end
  self
end