Skip to content

Instantly share code, notes, and snippets.

@olalonde
Created April 13, 2014 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olalonde/10596870 to your computer and use it in GitHub Desktop.
Save olalonde/10596870 to your computer and use it in GitHub Desktop.
var _ = require('underscore'),
inflection = require('inflection'),
path = require('path');
function join (arr) {
return path.join.apply(null, arr);
}
function map (app, context) {
context = _.extend({
basepath: '/'
}, context);
function generate_routes (name, resource, is_singleton, cb) {
if (!resource)
throw new TypeError('Error creating ' + name + ' route: no resource object passed');
if (typeof cb !== 'function')
cb = function () {};
var plural_name = is_singleton ? '' : inflection.pluralize(name);
var id_param = is_singleton ? '' : ':' + name;
var collection_routes = is_singleton ? [] : [
[ 'get', '', 'index' ],
[ 'get', 'new', 'new' ],
[ 'post', '', 'create' ]
].map(function (row) {
return [ row[0], [ plural_name, row[1] ], row[2] ];
});
var instance_routes = [
[ 'get', '', 'show' ],
[ 'get', 'edit', 'edit' ],
[ 'put', '', 'update' ],
[ 'delete', '', 'destroy' ]
].map(function (row) {
return [ row[0], [ plural_name, id_param, row[1] ], row[2] ];
});
var routes = collection_routes.concat(instance_routes).map(function (row) {
return [ row[0], join([ context.basepath ].concat(row[1])), row[2] ];
});
var valid_routes = _.filter(routes, function (route) {
if (typeof resource[route[2]] === 'function') return true;
});
_.each(valid_routes, function (route) {
app[route[0]](route[1], resource[route[2]]);
});
return valid_routes.concat(cb(map(app, {
parent_context: context,
basepath: join([ context.basepath, plural_name, id_param ])
})) || []);
}
function resource (name, resource, cb) {
return generate_routes(name, resource, true, cb);
}
function resources (name, resource, cb) {
return generate_routes(name, resource, false, cb);
}
return {
resource: resource,
resources: resources
};
};
module.exports = map;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment