This post originated from an RSS feed registered with Ruby Buzz
by Matthias Georgi.
Original Post: DRY Up Your Url Helpers
Feed Title: Matthias Georgi
Feed URL: http://feeds.feedburner.com/matthias-georgi?format=xml
Feed Description: Webdev, Gamedev and Interaction Design.
This tutorial shows you how to simplify url generation in combination with RESTful resources by extending the url_for helper. This approach will also work with nested routes and other helpers like form_tag and link_to. Each resource will have its own unique url, which is generated by calling url_for(resource).
First we need a simple example. We have 2 models: User and Article. For our url generation to work we have to add following code to our models:
This is necessary for nested routes to play nicely with our url generation code. We are now able to find the parameters for each record to generate an unique URL.
Our nested routes are defined in config/routes.rb:
map.resources :users do |user|
user.resources :articles
end
And now add the following module into your lib folder and include the module in both your application controller and application helper:
So how can you use this stuff actually?
It is pretty easy: just pass the record instead of the url hash and the unique url will be generated automatically. This works for helpers like url_for, form_tag or link_to.
Some examples:
If anybody is interested I will release this stuff as plugin. I think other helpers could benefit as well as you can pass your records around and each helper may generate the appropriate url.