Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Support named params, closes #16

  • Loading branch information...
commit e808060a2ab4a033ef3fcea28134930840d55260 1 parent 9e3378a
@1602 authored
Showing with 25 additions and 7 deletions.
  1. +18 −7 lib/railway_routes.js
  2. +7 −0 test/railway_routes_test.js
View
25 lib/railway_routes.js
@@ -157,26 +157,37 @@ Map.prototype.addPath = function (templatePath, action, helperName) {
// TODO: think about adding to `path_to` routes by reg ex
return;
}
- var paramsLength = templatePath.match(/\/:/g);
+ var paramNames = [];
+ var paramsLength = templatePath.match(/\/:\w*/g);
+ if (paramsLength) {
+ paramNames = paramsLength.map(function (p) {
+ return p.substr(2);
+ });
+ }
paramsLength = paramsLength === null ? 0 : paramsLength.length;
- var optionalParamsLength = templatePath.match(/\/:\w*\??/);
+ var optionalParamsLength = templatePath.match(/\/:\w*\?/);
+ if (optionalParamsLength)
optionalParamsLength = optionalParamsLength ? optionalParamsLength.length : 0;
helperName = helperName || this.urlHelperName(templatePath, action);
// already defined? not need to redefine
- if (this.pathTo[helperName]) return;
+ if (helperName in this.pathTo) return;
- this.pathTo[helperName] = function () {
- if (arguments.length < (paramsLength - optionalParamsLength)) {
- return '';
+ this.pathTo[helperName] = function (objParam) {
+ // TODO: thing about removing or rewriting it
+ // if (arguments.length < (paramsLength - optionalParamsLength) || ) {
+ // return '';
// throw new Error('Expected at least ' + paramsLength + ' params for build path ' + templatePath + ' but only ' + arguments.length + ' passed');
- }
+ // }
var value, arg, path = templatePath;
for (var i = 0; i < paramsLength; i += 1) {
value = null;
arg = arguments[i];
+ console.log(objParam, paramNames, i);
if (arg && typeof arg.to_param == 'function') {
value = arg.to_param();
+ } else if (paramNames[i] && objParam && objParam[paramNames[i]]) {
+ value = objParam[paramNames[i]];
} else if (arg && typeof arg === 'object' && arg.id && arg.constructor.name !== 'ObjectID') {
value = arg.id;
} else {
View
7 test/railway_routes_test.js
@@ -159,3 +159,10 @@ it('should handle question mark after param name', function (test) {
test.equals(map.pathTo.test('param'), '/test/param');
test.done();
});
+
+it('should allow named parameters in url helpers', function (test) {
+ var map = new routes.Map(fakeApp([]), fakeBridge());
+ map.get('/testme/:p1/:p2', 'test#me');
+ test.equals(map.pathTo.testme({p1: 'hello', p2: 'world'}), '/testme/hello/world');
+ test.done();
+});
Please sign in to comment.
Something went wrong with that request. Please try again.