master/lib/guard/hook.rb

56 lines
1.4 KiB
Ruby
Raw Normal View History

2011-04-10 23:08:43 +00:00
module Guard
module Hook
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
# When passed a sybmol, #hook will generate a hook name
# from the symbol and calling method name. When passed
# a string, #hook will turn the string into a symbol
# directly.
def hook(event, *args)
hook_name = if event.is_a? Symbol
2011-04-10 23:08:43 +00:00
calling_method = caller[0][/`([^']*)'/, 1]
"#{calling_method}_#{event}".to_sym
2011-04-10 23:08:43 +00:00
else
event.to_sym
2011-04-10 23:08:43 +00:00
end
if ENV["GUARD_ENV"] == "development"
UI.info "\nHook :#{hook_name} executed for #{self.class}"
end
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
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)
callbacks[[guard_class, event]].include?(listener)
2011-04-10 23:08:43 +00:00
end
def notify(guard_class, event, *args)
2011-04-10 23:08:43 +00:00
callbacks[[guard_class, event]].each do |listener|
listener.call(guard_class, event, *args)
2011-04-10 23:08:43 +00:00
end
end
def reset_callbacks!
2011-04-10 23:08:43 +00:00
@callbacks = nil
end
end
end
end