2011-10-17 01:09:12 +00:00
|
|
|
class Pry
|
|
|
|
class Hooks
|
|
|
|
|
|
|
|
def initialize
|
|
|
|
@hooks = {}
|
|
|
|
end
|
|
|
|
|
2011-11-15 13:49:11 +00:00
|
|
|
# Add a new hook to be executed for the `name` even.
|
|
|
|
# @param [Symbol] name The name of the event.
|
|
|
|
# @param [Symbol] hook_function_name The name of the hook.
|
2011-10-17 01:09:12 +00:00
|
|
|
# @param [#call] callable The callable.
|
|
|
|
# @yield The block to use as the callable (if `callable` parameter not provided)
|
2011-11-15 13:49:11 +00:00
|
|
|
def add_hook(name, hook_function_name, callable=nil, &block)
|
|
|
|
@hooks[name] ||= {}
|
2011-10-17 01:09:12 +00:00
|
|
|
|
|
|
|
if block
|
2011-11-15 13:49:11 +00:00
|
|
|
@hooks[name][hook_function_name] = block
|
2011-10-17 01:09:12 +00:00
|
|
|
elsif callable
|
2011-11-15 13:49:11 +00:00
|
|
|
@hooks[name][hook_function_name] = callable
|
2011-10-17 01:09:12 +00:00
|
|
|
else
|
|
|
|
raise ArgumentError, "Must provide a block or callable."
|
|
|
|
end
|
|
|
|
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2011-11-15 13:49:11 +00:00
|
|
|
# Execute the list of hooks for the `name` event.
|
|
|
|
# @param [Symbol] name The name of the event.
|
|
|
|
# @param [Array] args The arguments to pass to each hook function.
|
|
|
|
# @return [Hash] The return values for each of the hook functions.
|
2011-10-17 01:09:12 +00:00
|
|
|
def exec_hook(name, *args, &block)
|
2011-11-15 13:49:11 +00:00
|
|
|
@hooks[name] ||= {}
|
|
|
|
Hash[@hooks[name].each.map { |k, v| [k, v.call(*args, &block)] }]
|
2011-10-17 01:09:12 +00:00
|
|
|
end
|
|
|
|
|
2011-11-15 13:49:11 +00:00
|
|
|
# Return the number of hook functions registered for the `name` event.
|
|
|
|
# @param [Symbol] name The name of the event.
|
|
|
|
# @return [Fixnum] The number of hook functions for the `name` event.
|
2011-11-12 13:03:02 +00:00
|
|
|
def hook_count(name)
|
2011-11-15 13:49:11 +00:00
|
|
|
@hooks[name] ||= {}
|
2011-11-12 13:03:02 +00:00
|
|
|
@hooks[name].size
|
|
|
|
end
|
|
|
|
|
2011-11-15 13:49:11 +00:00
|
|
|
# Return the hash of hook names / hook functions for a
|
|
|
|
# given event.
|
|
|
|
# @param [Symbol] name The name of the event.
|
|
|
|
# @return [Hash]
|
|
|
|
def get_hook(name, hook_function_name)
|
|
|
|
@hooks[name] ||= {}
|
|
|
|
@hooks[name][hook_function_name]
|
2011-10-17 01:09:12 +00:00
|
|
|
end
|
|
|
|
|
2011-11-15 13:49:11 +00:00
|
|
|
# Delete a hook for an event.
|
|
|
|
# @param [Symbol] name The name of the event.
|
|
|
|
# @param [Symbol] hook_function_name The name of the hook.
|
|
|
|
# to delete.
|
|
|
|
# @return [#call] The deleted hook.
|
|
|
|
def delete_hook(name, hook_function_name)
|
|
|
|
@hooks[name] ||= {}
|
|
|
|
@hooks[name].delete(hook_function_name)
|
|
|
|
end
|
|
|
|
|
|
|
|
# Clear all hooks functions for a given event.
|
|
|
|
# @param [String] name The name of the event.
|
|
|
|
def clear(name)
|
|
|
|
@hooks[name] = {}
|
2011-10-17 01:09:12 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|