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
:nameand:eventare defined, it searches for a callback that matches both:nameand:event. Otherwise, it matches one or the other. \$\endgroup\$