diff --git a/lib/forever/monitor.js b/lib/forever/monitor.js index c467b809..b61829d5 100644 --- a/lib/forever/monitor.js +++ b/lib/forever/monitor.js @@ -21,6 +21,7 @@ var sys = require('sys'), // Creates a new instance of forever with specified params. // var Monitor = exports.Monitor = function (script, options) { + var self = this; events.EventEmitter.call(this); // @@ -90,6 +91,20 @@ var Monitor = exports.Monitor = function (script, options) { if (this.errFile) { this.stderr = fs.createWriteStream(this.errFile, { flags: 'a+', encoding: 'utf8', mode: 0666 }); } + + // + // Last if any hooks have been passed in attach + // this instance to them + // + if (options.hooks.length > 0) { + options.hooks.forEach(function (hook) { + if (typeof hook === 'function') { + return hook(self); + } + + hook.attach(self); + }); + } }; // Inherit from events.EventEmitter diff --git a/test/fixtures/test-hook.js b/test/fixtures/test-hook.js new file mode 100644 index 00000000..7cbdc07b --- /dev/null +++ b/test/fixtures/test-hook.js @@ -0,0 +1,23 @@ +/* + * test-hook.js: Test hook fixture for raising an event on forever.Monitor `exit` + * + * (C) 2010 and Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + util = require('util'); + +var TestHook = exports.TestHook = function () { + events.EventEmitter.call(this); +}; + +util.inherits(TestHook, events.EventEmitter); + +TestHook.prototype.attach = function (monitor) { + var self = this; + monitor.on('exit', function () { + self.emit.apply(['hook-exit'].concat(arguments)); + }); +}; \ No newline at end of file diff --git a/test/hook-test.js b/test/hook-test.js new file mode 100644 index 00000000..499c468f --- /dev/null +++ b/test/hook-test.js @@ -0,0 +1,41 @@ +/* + * hook-test.js: Tests for forever-based hooks + * + * (C) 2010 and Charlie Robbins + * MIT LICENCE + * + */ + + var sys = require('sys'), + assert = require('assert'), + path = require('path'), + vows = require('vows'), + forever = require('../lib/forever'), + TestHook = require('./fixtures/test-hook').TestHook; + + vows.describe('forever/spin-restart').addBatch({ + "When using forever": { + "and spawning a script that spin restarts": { + "with a simple hook": { + topic: function () { + var script = path.join(__dirname, '..', 'examples', 'always-throw.js'), + child; + + child = new (forever.Monitor)(script, { + silent: true, + max: 1, + hooks: [ + new TestHook() + ] + }); + + child.on('exit', this.callback.bind({}, null)); + child.start(); + }, + "should raise the `hook-exit` event": function (err, child, spinning) { + assert.isTrue(spinning); + } + } + } + } + }).export(module);