Permalink
Browse files

Nested routes on collection

  • Loading branch information...
1 parent aeb146c commit 6ae6cc6dbf20311d8034b24c1a5f4be9fc260ee9 @1602 committed Feb 14, 2013
Showing with 62 additions and 2 deletions.
  1. +28 −2 lib/railway_routes.js
  2. +34 −0 test/railway_routes_test.js
View
30 lib/railway_routes.js
@@ -42,6 +42,8 @@ function Map(app, bridge) {
this.pathTo = {};
this.dump = [];
this.middlewareStack = [];
+ this.camelCaseHelperNames = false;
+ this.nestedRoutesOnCollection = false;
}
/**
@@ -120,13 +122,13 @@ Map.prototype.root = function (handler, middleware, options) {
var path;
if (typeof subpath === 'string') {
var prefix = '';
- if (options.collection) {
+ if (options.collection || this.nestedRoutesOnCollection) {
prefix = this.globPath.replace(/:[^\/]*_id\/$/, '');
} else {
prefix = this.globPath;
}
path = prefix + subpath.replace(/^\/|\/$/, '');
- } else { // regex???
+ } else { // regex
path = subpath;
}
@@ -491,3 +493,27 @@ Map.prototype.addRoutes = function (path, customBridge) {
return r;
};
+/**
+ * Syntax sugar for nested routes for collection
+ * this method only can be used in context of nested actions
+ *
+ * Example:
+ *
+ * map.resources('posts', function (post) {
+ * post.collection(function (posts) {
+ * posts.del('destroyAll', 'posts#destroyAll');
+ * });
+ * });
+ */
+Map.prototype.collection = function (actions) {
+ this.nestedRoutesOnCollection = true;
+ actions(this);
+ this.nestedRoutesOnCollection = false;
+ return this;
+};
+
+function camelize(str) {
+ return str.replace(/_+(.)/g, function (all, first) {
+ return first.toUpperCase();
+ });
+}
View
34 test/railway_routes_test.js
@@ -232,3 +232,37 @@ it('should only replace last collection_id when collection: true', function (tes
]);
test.done();
});
+
+it('should camelize helper names', function (test) {
+ var map = new routes.Map(fakeApp([]), fakeBridge());
+ map.camelCaseHelperNames = true;
+ map.resources('posts', function (post) {
+ post.resources('comments');
+ });
+ test.deepEqual(Object.keys(map.pathTo), [
+ 'postComments',
+ 'newPostComment',
+ 'editPostComment',
+ 'postComment',
+ 'posts',
+ 'newPost',
+ 'editPost',
+ 'post'
+ ]);
+ test.done();
+});
+
+it('should provide convenient api for collection-wide nested routes', function (test) {
+ var paths = [];
+ var map = new routes.Map(fakeApp(paths), fakeBridge());
+ map.resources('posts', function(post) {
+ post.collection(function(posts) {
+ posts.del('destroyAll', 'posts#destroyAll');
+ });
+ });
+ test.deepEqual(
+ paths[0].join(' '),
+ 'DEL /posts/destroyAll posts#destroyAll'
+ );
+ test.done();
+});

0 comments on commit 6ae6cc6

Please sign in to comment.