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
-
#bind(evid, handler) ⇒ Object
Binds an event handler, which is a Hash of the form:.
-
#emit(evid, *args) ⇒ Object
Fires an evid event with the given arguments.
-
#on(evid, opts = {}, &callback) ⇒ Object
Binds a block to the specified event id.
-
#once(evid, opts = {}, &callback) ⇒ Object
Binds a block to the specified event id, to be executed only once.
-
#unbind(handler) ⇒ Object
Unbinds the given handler.
Instance Method Details
#bind(evid, handler) ⇒ Object
Binds an event handler, which is a Hash of the form:
{ :evid => Symbol, :id => Symbol, :repeat => Boolean, :proc => Proc }
See Evented#on and 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 |
#emit(evid, *args) ⇒ Object
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 |
#on(evid, opts = {}, &callback) ⇒ Object
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 |
#once(evid, opts = {}, &callback) ⇒ Object
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 |
#unbind(handler) ⇒ Object
Unbinds the given handler.
21 22 23 |
# File 'lib/safubot/evented.rb', line 21 def unbind(handler) @handlers[handler[:evid]].delete(handler[:id]) end |