Permalink
Browse files

Fix optional params handling, as per #16

  • Loading branch information...
1 parent d6600fe commit 9e3378ad5407032189b1d5ffb34319d84fb9c807 @1602 committed Jan 24, 2013
Showing with 9 additions and 2 deletions.
  1. +9 −2 lib/railway_routes.js
View
@@ -159,13 +159,15 @@ Map.prototype.addPath = function (templatePath, action, helperName) {
}
var paramsLength = templatePath.match(/\/:/g);
paramsLength = paramsLength === null ? 0 : paramsLength.length;
+ var optionalParamsLength = templatePath.match(/\/:\w*\??/);
+ optionalParamsLength = optionalParamsLength ? optionalParamsLength.length : 0;
helperName = helperName || this.urlHelperName(templatePath, action);
// already defined? not need to redefine
if (this.pathTo[helperName]) return;
this.pathTo[helperName] = function () {
- if (arguments.length < paramsLength) {
+ if (arguments.length < (paramsLength - optionalParamsLength)) {
return '';
// throw new Error('Expected at least ' + paramsLength + ' params for build path ' + templatePath + ' but only ' + arguments.length + ' passed');
}
@@ -180,7 +182,12 @@ Map.prototype.addPath = function (templatePath, action, helperName) {
} else {
value = arg && arg.toString ? arg.toString() : arg;
}
- path = path.replace(/:\w*/, '' + value);
+ var matchOptional = path.match(/:(\w*\??)/);
+ if (matchOptional && matchOptional[1].substr(-1) === '?' && !value) {
+ path = path.replace(/\/:\w*\??/, '');
+ } else {
+ path = path.replace(/:\w*\??/, '' + value);
+ }
}
if (arguments[paramsLength]) {
var query = [];

0 comments on commit 9e3378a

Please sign in to comment.