The maze book for programmers!
mazesforprogrammers.com

Algorithms, circle mazes, hex grids, masking, weaving, braiding, 3D and 4D grids, spheres, and more!

DRM-Free Ebook

The Buckblog

assorted ramblings by Jamis Buck

Route#to_s

19 February 2007 — 1-minute read

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

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.

This works well also: puts ActionController::Routing::Routes.routes

How about sorting the routes first?

ActionController::Routing::Routes.named_routes.routes.sort_by(&:to_s)

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.

What are you using for your syntax highlighting on your blog?

Mephisto comes with a syntax highlighting module. It uses CodeRay under the covers.

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?

Justin, yes, you’ll need to style it up. CodeRay has a couple of different CSS stylesheets you can drop into your mephisto theme.

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:

map.resources :some_resource, :collection=>{:some_action=>:any}

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.

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.