Module: Guard::Plugin::Hooker

Included in:
Base
Defined in:
lib/guard/plugin/hooker.rb

Overview

Guard has a hook mechanism that allows you to insert callbacks for individual Guard plugins. By default, each of the Guard plugin instance methods has a “_begin” and an “_end” hook. For example, the Guard::Plugin#start method has a :start_begin hook that is runs immediately before Guard::Plugin#start, and a :start_end hook that runs immediately after Guard::Plugin#start.

Read more about [hooks and callbacks on the wiki](github.com/guard/guard/wiki/Hooks-and-callbacks).

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_callback(listener, guard_plugin, events) ⇒ Object

Add a callback.



33
34
35
36
37
# File 'lib/guard/plugin/hooker.rb', line 33

def self.add_callback(listener, guard_plugin, events)
  Array(events).each do |event|
    callbacks[[guard_plugin, event]] << listener
  end
end

.callbacksObject

Get all callbacks registered for all Guard plugins present in the Guardfile.



23
24
25
# File 'lib/guard/plugin/hooker.rb', line 23

def self.callbacks
  @callbacks ||= Hash.new { |hash, key| hash[key] = [] }
end

.notify(guard_plugin, event, *args) ⇒ Object

Notify a callback.



45
46
47
48
49
# File 'lib/guard/plugin/hooker.rb', line 45

def self.notify(guard_plugin, event, *args)
  callbacks[[guard_plugin, event]].each do |listener|
    listener.call(guard_plugin, event, *args)
  end
end

.reset_callbacks!Object

Reset all callbacks.



53
54
55
# File 'lib/guard/plugin/hooker.rb', line 53

def self.reset_callbacks!
  @callbacks = nil
end

Instance Method Details

#hook(event, *args) ⇒ Object

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.

Here, when Base#run_all is called, #hook will notify callbacks registered for the “run_all_foo” event.

When event is a String, #hook will directly turn the String into a Symbol.

When Base#run_all is called, #hook will notify callbacks registered for the “foo_bar” event.

Examples:

Add a hook with a Symbol


def run_all
  hook :foo
end

Add a hook with a String


def run_all
  hook "foo_bar"
end


86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/guard/plugin/hooker.rb', line 86

def hook(event, *args)
  hook_name = if event.is_a? Symbol
                calling_method = caller[0][/`([^']*)'/, 1]
                "#{ calling_method }_#{ event }"
              else
                event
              end

  ::Guard::UI.debug "Hook :#{ hook_name } executed for #{ self.class }"

  Hooker.notify(self, hook_name.to_sym, *args)
end