Using the Router

vahek edited this page Feb 14, 2013 · 18 revisions

Generating Routes

var r = new geddy.RegExpRouter();

a very simple route:


optional groups are contained in (parens)


when either the controller or action aren’t present in the URL, you can map them in the to() method


you can specify the HTTP method to match, otherwise it will assume any method will do:

r.match('/:controller/:id', 'GET').to({action:'show'});

you can force keys to match a specific pattern by passing a hash of {key: pattern} pairs to the where() method

r.match('/:controller/:action/:id(.:format)', 'GET').where({id: /\d+/ });

Generating Resources


is equivalent to the following:

r.match('/snow_dogs(.:format)','GET').to({controller: 'SnowDogs', action: 'index'});
r.match('/snow_dogs/add(.:format)','GET').to({controller: 'SnowDogs', action: 'add'});
r.match('/snow_dogs/:id(.:format)','GET').to({controller: 'SnowDogs', action: 'show'});
r.match('/snow_dogs/:id/edit(.:format)','GET').to({controller: 'SnowDogs', action: 'edit'});
r.match('/snow_dogs(.:format)','POST').to({controller: 'SnowDogs', action: 'create'});
r.match('/snow_dogs/:id(.:format)','PUT').to({controller: 'SnowDogs', action: 'update'});
r.match('/snow_dogs/:id(.:format)','DELETE').to({controller: 'SnowDogs', action: 'remove'});

Generating URLs

this will probably be mixed in to the controller as a local method

you pass a params hash

r.url({controller:'SnowDogs', action: 'show', id: 5});  // =>  '/snow_dogs/5'

optional segments are included only if all the inside params are accounted for

r.url({controller:'SnowDogs', action: 'show', id: 5, format: 'json'}); 
// =>  '/snow_dogs/5.json'

if you fail to specify a controller or action, the defaults “Application” and “index” will be used, respectively.

Extra Params

extra params that aren’t folded into the route will be appended to the query string

r.url({controller:'SnowDogs', action: 'show', id: 5, geddy: 'awesome'});
// =>  '/snow_dogs/5?geddy=awesome'

similarly, any QS params that are parsed with a request will simply be added to the params hash

Internal Stuff

only important if you’re hacking on Geddy

finding the first route that matches a request URI / method

r.first('/snow_dogs/5', 'GET');
// => {controller:'SnowDogs', action: 'show', id: 5}

QS params are to be passed in with the path:

r.first('/snow_dogs/5?danke=schoen&high=5', 'GET');
// => {controller:'SnowDogs', action: 'show', id: 5, danke: 'schoen', high: 5}


optional groups CANNOT currently be nested – this will likely freak it right out

by default, all keys in a route are subjected to the regex match /[\w\-]+/

EXCEPT controller & action, which have the limitation that they may not begin with a numeric digit: /[a-zA-Z\-\_][\w\-]+/

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.