module Safubot::Evented

A mixin granting simple event firing and handler binding.

Public Instance Methods

bind(evid, handler) click to toggle source

Binds an event handler, which is a Hash of the form:

{ :evid => Symbol, :id => Symbol, :repeat => Boolean, :proc => Proc }

See on and once for sugar.

# File lib/safubot/evented.rb, line 10
def bind(evid, handler)
  @handlers ||= {}
  @handlers[evid] ||= {}
  handler[:evid] = evid
  handler[:id] ||= @handlers[evid].length
  @handlers[evid][handler[:id]] = handler
end
emit(evid, *args) click to toggle source

Fires an evid event with the given arguments.

# File lib/safubot/evented.rb, line 36
def emit(evid, *args)
  return unless @handlers && @handlers[evid]
  @handlers[evid].each do |id, handler| 
        begin
          handler[:proc].call(*args)
        ensure
          @handlers[evid].delete(id) if !handler[:repeat]
        end
  end
end
on(evid, opts={}, &callback) click to toggle source

Binds a block to the specified event id. Returns the bound handler.

# File lib/safubot/evented.rb, line 25
def on(evid, opts={}, &callback)
  bind(evid, { :repeat => true, :proc => callback }.merge(opts))
end
once(evid, opts={}, &callback) click to toggle source

Binds a block to the specified event id, to be executed only once. Returns the bound handler.

# File lib/safubot/evented.rb, line 31
def once(evid, opts={}, &callback)
  bind(evid, { :repeat => false, :proc => callback }.merge(opts))
end
unbind(handler) click to toggle source

Unbinds the given handler.

# File lib/safubot/evented.rb, line 19
def unbind(handler)
  @handlers[handler[:evid]].delete(handler[:id])
end