Version 1
I need a way to store and retrieve callbacks in Ruby. So I made a Callbacks
class. Any suggestions would be greatly appreciated, thank you!
class Callbacks
def initialize
# name: name of callback
# event: event of which it belongs
# callback: block to call
@callbacks = []
end
def add name, event, &block
if block_given?
@callbacks << {
name: name,
event: event,
callback: block
}
end
end
def get options={}
name = options[:name]
event = options[:event]
@callbacks.each do |h|
if name and event
return h if h[:name] == name and h[:event] == event
else
return h if h[:name] == name or h[:event] == event
end
end
nil
end
end
UPDATE: Both the name and event can be the same. So there could be two callbacks with a name of :all
and with an event of :join
.
Version 2
My second attempt at this isn't that much different that version one. The main difference lies within the get
function. For the updated version of the add
function see blufox's answer.
def get options={}
name, event = options.values_at(:name, :event)
return @callbacks[options] if name and event
@callbacks.inject [] do |a, (k, _)|
a << k if k[:name] == name or k[:event] == event
a
end
end
The requirements for this function are.
- One match is returned if both
:name
and:event
are supplied. - An array of matches are returned if either
:name
or:event
are supplied.
Those are the only requirements. Any suggestions would be wonderful. Thank you.
:name
and:event
are defined, it searches for a callback that matches both:name
and:event
. Otherwise, it matches one or the other. – Bryan Dunsmore May 31 '12 at 18:34