Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created April 16, 2012 05:34
Show Gist options
  • Save gerardpaapu/2396503 to your computer and use it in GitHub Desktop.
Save gerardpaapu/2396503 to your computer and use it in GitHub Desktop.
var Advice = function (type, advice) {
this.type = type;
this.advice = advice;
};
Advice.adviseMethod = function (method, advice, combine) {
if (typeof combine != 'function') { // TODO: don't use typeof
combine = Advice.Types[combine] || Advice.Types.none;
}
advice = advice || function () {};
return combine(method, advice);
};
Advice.prototype.adviseMethod = function (method) {
return Advice.adviseMethod(method, this.advice, this.type);
};
Advice.Types = {
// {{{ Advice.Types
before: function before (method, advice) {
return function () {
advice.apply(this, arguments);
method.apply(this, arguments);
};
},
after: function after(method, advice) {
return function () {
var result = method.apply(this, arguments);
advice.apply(this, arguments);
return result;
};
},
around: function around(method, advice) {
return function () {
var args = [method].concat(arguments);
return method.apply(this, arguments);
};
},
instead: function instead(method, advice) {
return advice;
},
none: function (method, advice) {
return method;
},
when: function when(method, advice) {
return function () {
return advice.apply(this, arguments) &&
method.apply(this, arguments);
};
},
unless: function unless(method, advice) {
return function () {
return advice.apply(this, arguments) ||
method.apply(this, arguments);
};
}
// }}}
};
var Advisable = function (method) {
this.method = method;
this.stack = [];
};
Advisable.prototype.getAdvisedMethod = function () {
return this.stack.reduce(function (method, advice) {
return advice.adviseMethod(method);
}, this.method);
};
Advisable.prototype.apply = function (ctx, args) {
return this.getAdvisedMethod().apply(ctx, args);
};
Advisable.prototype.toFunction = function () {
var advisable = this;
return function () {
return advisable.apply(this, arguments);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment