Route#to_s
Here’s a nifty trick. Route#to_s exists. Why is this cool?
1 2 3 |
ActionController::Routing::Routes.routes.each do |r| puts r end |
This will give you a list of all of the routes you have defined, in a very human-consumable format. It’s great if you are trying to figure out why Rails is having problems accepting a URL that you think it should be accepting.
Similarly, you can list all of your named routes:
1 2 3 |
ActionController::Routing::Routes.named_routes.routes.each do |name, route| puts "%20s: %s" % [name, route] end |
This is especially handy if you are using map.resources
, where there are lots of named routes being generated for you behind the scenes.
Reader Comments
Hi Jamis, welcome back, and thank you for the tip! Adam
19 Feb 2007
Wow – you must have read my mind. I was wrestling a bit last night getting some routes to work (ended up being an obvious ordering problem), and was looking for something like this. I’ll tuck this away for later.
Thanks.
19 Feb 2007
This works well also: puts ActionController::Routing::Routes.routes
20 Feb 2007
How about sorting the routes first?
ActionController::Routing::Routes.named_routes.routes.sort_by(&:to_s)
20 Feb 2007
Sascha, although sorting the routes might have some value, generally I’ve wanted to see them in the order they were defined, since that’s the order that the routing engine will try to apply them. If you’re having problems with a route not being recognized like you expect, it’s usually because you need to define it further toward the top of the file, and showing them in their natural order will reveal that dependency.
20 Feb 2007
What are you using for your syntax highlighting on your blog?
21 Feb 2007
Mephisto comes with a syntax highlighting module. It uses CodeRay under the covers.
21 Feb 2007
Did you do any hacking/editing to get it to work? I saw it says its built in, but it doesn’t seem to highlight it. Are you using custom css or something?
21 Feb 2007
Justin, yes, you’ll need to style it up. CodeRay has a couple of different CSS stylesheets you can drop into your mephisto theme.
21 Feb 2007
Sweet! This solved another problem I was wrestling with – I noticed that when you view the output of the routes, the default routes (:controller/:action/:id) were listed as ANY.
I often find that I want to add an action to a mapped resource that can accept both get and post, and now I can just do:
This will oddly show up as a GET route when showing the routes, but it allows for the get or post action in the browser.
23 Feb 2007
The plugin routing_navigator generates an AJAX toolbar to view/fool around with your routes. I have found it handy to understand what is going on.
8 Mar 2007