Clone this wiki locally

Hooks

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

Callbacks

You can set your callback for a specific Guard in your Guardfile with the Guard::DSL.callback method. There are two ways to define your callbacks:

With a block

The first argument to Guard::Dsl#callback is the hook of interest. The block contains the code to run. For example, to have Guard open TextMate when it first starts up:

Without a block

If you have more complex code to run, you can create a separate object to contain that code. In order for the callback to run, it must have a #call (or .call if it's a module) method that receives the class of the Guard associated with the callback, the hook event, and a splat of other arguments. For Guard::Dsl#callback, you pass the object (or the module) and the hook(s) you are interested in. Here is an example of a Timer plugin.

For the default "_begin" hooks, the *args that are passed to #call are the matched files that Guard has detected changes on. For the default "_end" hooks, *args are the results of the Guard action that was executed.

NOTES / Caveats

Currently, callbacks are fired only if the given plugin implements the related method, e.g. Guard-Rspec doesn't currently implement stop, so callbacks for :stop_begin and :stop_end won't be called. The quick workaround is to add these methods through monkey-patching, but of course, caution is advised when doing so:

Developers

If you are developing a Guard and want end users or other gems to be able to hook into certain parts of your code, then you can create a custom hook with the #hook method. You define the hook's name with either a symbol or string. If passed a symbol, the hook name will be the name of the calling method with the symbol appended. If passed a string, the hook name will be the string.

moduleGuardclassMyGuard < Plugindefstart# some code
hook :custom_hook_1# this hook's name will be :start_custom_hook_l# more code
hook "custom_hook_2"# this hook's name will be :custom_hook_2# rest of codeend# the default hooks :start_begin and :start_end will still be availableendend

This wiki and the Guard README document contains a
lot of information, please take your time and read these instructions carefully.