Skip to content

Commit

Permalink
add named params
Browse files Browse the repository at this point in the history
  • Loading branch information
Caolan McMahon committed Oct 28, 2010
1 parent d8d1ebf commit 4883cd3
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
6 changes: 5 additions & 1 deletion README.md
Expand Up @@ -12,7 +12,7 @@ regular expressions for matching URLs and calling an associated function.
'/about': function(req, res, next){
...
},
'/user': function(req, res, next){
'/user/:id': function(req, res, next, id){
...
},
'/user/posts': function(req, res, next){
Expand All @@ -28,6 +28,10 @@ Dispatch can be used with a straight-forward object literal containing view
functions keyed by URL. As you can see from the last URL in the list, captured
groups are passed to the matching function as an argument.

You can also use :named parameters in a URL, which is just a more readable way
of capturing ([^\/]+). Named parameters are passed to the matched function in
the same way as normal regular expression groups.

So far so predictable. However, it is also possible to nest these objects as
you see fit:

Expand Down
4 changes: 3 additions & 1 deletion lib/dispatch.js
Expand Up @@ -32,7 +32,9 @@ function flattenKeys(obj, /*optional args: */acc, prefix, prev_method){
*/
function compileKeys(urls){
return urls.map(function(url){
url[0] = new RegExp('^' + url[0] + '$');
// replace named params with regexp groups
var pattern = url[0].replace(/\/:\w+/g, '(?:/([^\/]+))');
url[0] = new RegExp('^' + pattern + '$');
return url;
});
}
Expand Down
30 changes: 29 additions & 1 deletion test/test-dispatch.js
@@ -1,4 +1,4 @@
var dispatch = require('dispatch');
var dispatch = require('../lib/dispatch');

exports['simple match'] = function(test){
test.expect(3);
Expand Down Expand Up @@ -208,3 +208,31 @@ exports['whitespace between method and pattern'] = function (test) {
handle_req(request, 'response', 'next');
test.done();
};

exports['named param'] = function (test) {
var request = {url: '/abc/test123'};
dispatch({
'/:name/test\\d{3}': function(req, res, next, name){
test.equals(req, request);
test.equals(res, 'response');
test.equals(next, 'next');
test.equals(name, 'abc');
test.done();
}
})(request, 'response', 'next');
};

exports['nested named param'] = function (test) {
var request = {url: '/test/123'};
dispatch({
'/test': {
'/:param': function(req, res, next, name){
test.equals(req, request);
test.equals(res, 'response');
test.equals(next, 'next');
test.equals(name, '123');
test.done();
}
}
})(request, 'response', 'next');
};

0 comments on commit 4883cd3

Please sign in to comment.