Module: Beacon

Extended by:
Beacon
Included in:
Beacon
Defined in:
lib/beacon.rb

Instance Method Summary collapse

Instance Method Details

#fire(event, *args) ⇒ Object Also known as: trigger

Fire an event to be processed by all the watchers. You pass the event name and any arguments you want passed to the event handlers.

Beacon.fire(:some_event, "an argument", 2, "another")


8
9
10
11
12
# File 'lib/beacon.rb', line 8

def fire(event, *args)
  events[event].each do |callback|
    callback.call(*args)
  end
end

#watch(event, handler = nil, &default_handler) ⇒ Object Also known as: on

Register a callback for a given event. Each time you call fire then all the callbacks registered for that name will be called in order.

Beacon.watch :some_event do |foo, bar, baz|
  # do stuff with foo, bar, and baz
end

Instead of passing a block, you can pass any object that responds to #call. Like this:

class MyHandler
  def call(foo=1, bar=2, baz=3)
    puts foo, bar, baz
  end
end

Beacon.watch :some_event, MyHandler.new


32
33
34
35
36
37
38
# File 'lib/beacon.rb', line 32

def watch(event, handler=nil, &default_handler)
  if handler && block_given?
    raise ArgumentError, "You cannot register a handler with both a block and an object"
  end
  handler = handler || default_handler || raise(ArgumentError, "You must provide a handler")
  events[event] << handler
end