Introducing…
May 30, 2007 – 7:17 amMagic Routing! That’s right, the patch I submitted to Rails core long ago has finally been denied (bitsweat: “too much magic”), so I’m releasing it as a plugin instead.
Basically, magic_routing is an alternative to the to_param overriding that’s been going around. While URLs generated by overriding to_param are reasonably understandable (http://www.example.com/people/123-foo-bar), they’re not very memorable, since they still contain the meaningless (to the end user) ID - and stuffing ‘123-foo-bar’ into a parameter called ‘id’ is a little misleading. Magic Routing overcomes these problems by making it easy to use meaningful attributes from your ActiveRecord objects in your route. In the people example, we might use a login name (http://www.example.com/people/foo), with the route map.person ‘people/:username’, …
“But I’ve been able to do that all along,” you say?!? Yes, but here’s where the magic comes in… the :username route generates the example URL in just the same way you’d generate the ID-based url: <%= person_url(@person) %>. The Magic Routing plugin looks for attributes on your object that correspond to the named segments of the route (in this case, :username) and uses those attributes instead of to_param if it can. Want to change your username route back to an ID route? Just change the route definition to … ‘people/:id’ (and update your action) and you’re done.
See? Magic.
If you want to give it a shot, you can download or script/plugin install it from http://svn.mypulllist.com/svn/ext/magic_routing/. Comments are welcome!


One Response to “Introducing…”
Interesting. I can’t believe this was considered “too much magic”. I’ve always thought this is how it should work out of the box — having it magically use the :id is “too much magic”. At least this is consistent.
(I think I may just start using your plugin)
By simon on Aug 7, 2007