2011-04-10 23:08:43 +00:00
|
|
|
module Guard
|
|
|
|
module Hook
|
2011-04-29 22:40:12 +00:00
|
|
|
|
2011-04-10 23:08:43 +00:00
|
|
|
def self.included(base)
|
|
|
|
base.send :include, InstanceMethods
|
|
|
|
end
|
|
|
|
|
|
|
|
module InstanceMethods
|
2011-04-29 22:40:12 +00:00
|
|
|
# When +event+ is a Symbol, #hook will generate a hook name
|
|
|
|
# by concatenating the method name from where #hook is called
|
|
|
|
# with the given Symbol.
|
|
|
|
# Example:
|
|
|
|
# def run_all
|
|
|
|
# hook :foo
|
|
|
|
# end
|
|
|
|
# Here, when #run_all is called, #hook will notify callbacks
|
|
|
|
# registered for the "run_all_foo" event.
|
2011-04-29 22:49:46 +00:00
|
|
|
#
|
2011-04-29 22:40:12 +00:00
|
|
|
# When +event+ is a String, #hook will directly turn the String
|
|
|
|
# into a Symbol.
|
|
|
|
# Example:
|
|
|
|
# def run_all
|
|
|
|
# hook "foo_bar"
|
|
|
|
# end
|
|
|
|
# Here, when #run_all is called, #hook will notify callbacks
|
|
|
|
# registered for the "foo_bar" event.
|
2011-04-29 22:49:46 +00:00
|
|
|
#
|
2011-04-29 22:40:12 +00:00
|
|
|
# +args+ parameter is passed as is to the callbacks registered
|
|
|
|
# for the given event.
|
2011-04-18 00:06:45 +00:00
|
|
|
def hook(event, *args)
|
2011-04-16 21:02:13 +00:00
|
|
|
hook_name = if event.is_a? Symbol
|
2011-04-10 23:08:43 +00:00
|
|
|
calling_method = caller[0][/`([^']*)'/, 1]
|
2011-09-04 16:44:42 +00:00
|
|
|
"#{calling_method}_#{event}"
|
2011-04-10 23:08:43 +00:00
|
|
|
else
|
2011-09-04 16:44:42 +00:00
|
|
|
event
|
|
|
|
end.to_sym
|
2011-04-10 23:08:43 +00:00
|
|
|
|
2011-09-05 08:39:56 +00:00
|
|
|
UI.debug "Hook :#{hook_name} executed for #{self.class}"
|
2011-04-18 00:06:45 +00:00
|
|
|
|
|
|
|
Hook.notify(self.class, hook_name, *args)
|
2011-04-10 23:08:43 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class << self
|
|
|
|
def callbacks
|
|
|
|
@callbacks ||= Hash.new { |hash, key| hash[key] = [] }
|
|
|
|
end
|
|
|
|
|
2011-04-16 21:02:13 +00:00
|
|
|
def add_callback(listener, guard_class, events)
|
|
|
|
_events = events.is_a?(Array) ? events : [events]
|
2011-04-10 23:08:43 +00:00
|
|
|
_events.each do |event|
|
|
|
|
callbacks[[guard_class, event]] << listener
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def has_callback?(listener, guard_class, event)
|
2011-04-16 21:02:13 +00:00
|
|
|
callbacks[[guard_class, event]].include?(listener)
|
2011-04-10 23:08:43 +00:00
|
|
|
end
|
|
|
|
|
2011-04-18 00:06:45 +00:00
|
|
|
def notify(guard_class, event, *args)
|
2011-04-10 23:08:43 +00:00
|
|
|
callbacks[[guard_class, event]].each do |listener|
|
2011-04-18 00:06:45 +00:00
|
|
|
listener.call(guard_class, event, *args)
|
2011-04-10 23:08:43 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-04-16 21:02:13 +00:00
|
|
|
def reset_callbacks!
|
2011-04-10 23:08:43 +00:00
|
|
|
@callbacks = nil
|
|
|
|
end
|
|
|
|
end
|
2011-04-29 22:40:12 +00:00
|
|
|
|
2011-04-10 23:08:43 +00:00
|
|
|
end
|
|
|
|
end
|