I need a way to store and retrieve callbacks in Ruby, so I made a Callbacks
class. Any suggestions would be greatly appreciated.
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
:name
and:event
are defined, it searches for a callback that matches both:name
and:event
. Otherwise, it matches one or the other. – user12400 May 31 '12 at 18:34