Module: Safubot::Evented
- Included in:
- Bot, Twitter::Bot, XMPP::Bot
- Defined in:
- lib/safubot/evented.rb
Overview
A mixin granting simple event firing and handler binding.
Instance Method Summary (collapse)
-
- (Object) bind(evid, handler)
Binds an event handler, which is a Hash of the form:.
-
- (Object) emit(evid, *args)
Fires an evid event with the given arguments.
-
- (Object) on(evid, opts = {}, &callback)
Binds a block to the specified event id.
-
- (Object) once(evid, opts = {}, &callback)
Binds a block to the specified event id, to be executed only once.
-
- (Object) unbind(handler)
Unbinds the given handler.
Instance Method Details
- (Object) bind(evid, handler)
Binds an event handler, which is a Hash of the form:
{ :evid => Symbol, :id => Symbol, :repeat => Boolean, :proc => Proc }
See on[rdoc-ref:Safubot::Evented#on] and once[rdoc-ref:Safubot::Evented#once] for sugar.
11 12 13 14 15 16 17 |
# File 'lib/safubot/evented.rb', line 11 def bind(evid, handler) @handlers ||= {} @handlers[evid] ||= {} handler[:evid] = evid handler[:id] ||= @handlers[evid].length @handlers[evid][handler[:id]] = handler end |
- (Object) emit(evid, *args)
Fires an evid event with the given arguments.
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/safubot/evented.rb', line 41 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 |
- (Object) on(evid, opts = {}, &callback)
Binds a block to the specified event id. Returns the bound handler.
28 29 30 |
# File 'lib/safubot/evented.rb', line 28 def on(evid, opts={}, &callback) bind(evid, { :repeat => true, :proc => callback }.merge(opts)) end |
- (Object) once(evid, opts = {}, &callback)
Binds a block to the specified event id, to be executed only once. Returns the bound handler.
35 36 37 |
# File 'lib/safubot/evented.rb', line 35 def once(evid, opts={}, &callback) bind(evid, { :repeat => false, :proc => callback }.merge(opts)) end |
- (Object) unbind(handler)
Unbinds the given handler.
21 22 23 |
# File 'lib/safubot/evented.rb', line 21 def unbind(handler) @handlers[handler[:evid]].delete(handler[:id]) end |