jackson
Version:
Jackson, the web application framework
90 lines (76 loc) • 2.82 kB
JavaScript
// Generated by CoffeeScript 1.9.3
(function() {
var Router, extend, path, urlPattern,
slice = [].slice;
path = require('path');
urlPattern = require('url-pattern');
extend = require('./util').extend;
Router = (function() {
var _is;
function Router() {
this.routes = [];
}
Router.prototype.resource = function(pattern, controller, options) {
var dest;
dest = function(action) {
return [controller, action].join('#');
};
this.route('GET', pattern, dest('index'), options);
this.route('GET', path.join(pattern, ":id"), dest('show'), options);
this.route('POST', pattern, dest('create'), options);
this.route(['POST', 'PUT', 'PATCH'], path.join(pattern, ":id"), dest('update'), options);
return this.route('DELETE', pattern, dest('delete'), options);
};
Router.prototype.route = function(method, pattern, dest, options) {
var action, controller, i, len, m, ref, ref1, ref2;
if (method instanceof Array) {
for (i = 0, len = method.length; i < len; i++) {
m = method[i];
(ref = this.route).call.apply(ref, [this, m].concat(slice.call(Array.prototype.slice.call(arguments, 1))));
}
return;
}
if (!dest || typeof dest === 'object') {
ref1 = ['GET', method, pattern, dest], method = ref1[0], pattern = ref1[1], dest = ref1[2], options = ref1[3];
}
options || (options = {});
options.method = (options.method || method).toUpperCase();
options.pattern = urlPattern.newPattern(pattern);
if (typeof dest === 'string' && dest.indexOf('#') !== -1) {
ref2 = dest.split('#'), controller = ref2[0], action = ref2[1];
options.controller = controller;
options.action = action;
} else if (typeof dest === 'function') {
options.fn = dest;
} else {
throw new Error("Bad destination: " + dest + ". Must be a function or a string like 'Controller#action'");
}
return this.routes.push(options);
};
_is = function(controllerOrUrl, action) {
if (action) {
return this.controller === controllerOrUrl && (action === '*' || action === this.action);
} else {
return this.pattern.match(controllerOrUrl) != null;
}
};
Router.prototype.match = function(method, url) {
var i, len, match, ref, route;
ref = this.routes;
for (i = 0, len = ref.length; i < len; i++) {
route = ref[i];
if (route.method === method) {
if (match = route.pattern.match(url)) {
return extend({
params: match,
is: _is
}, route);
}
}
}
return false;
};
return Router;
})();
module.exports = Router;
}).call(this);