Rails: RESTful namespaces shall set you free
3
Being one of the its admirers, I try to conform to REST almost all the time, thanks to Rails support. One of the problems in following the REST model is the problem of resource naming. In its simplest forms, REST is about mapping each resource to a unique name with a set of conventional urls. The problem appears in a case when you need more than one view for some/all of your application resources (in the same format), or in other words, if some resources need to have colliding names.
A famous example of such a case is application with administration modules. Regularly, most of the resources need to be duplicated in another representation for the admin. For example, you already have a resource named 'Item' and you need another one with the same name and different representation for the admin.
Rails solves this problem with a handy feature: RESTful namespaces. RESTful routes could be managed in different namespaces to avoid names collision. What's elegant about it is that when you nest a resource in a namespace, it's mapped directly to an expected controller class that is a member in a module thats name is the same as the namespace. Also, the namespace contributes to the url helpers just as nested resources.
For example, while the configuration:
map.resources :items
maps to ItemsController and generates a set of helpers/routes like:
items_path() => /items item_path(id) => /items/id new_item_path() => /items/new edit_item_path(id) => /items/id/edit
, the configuration:
map.namespace :admin do |admin| admin.resources :items end
maps to Admin::ItemsController and generates a set of helpers/routes like:
admin_items_path() => /admin/items admin_item_path(id) => /admin/items/id new_admin_item_path() => /admin/items/new edit_admin_item_path(id) => /admin/items/id/edit
So, essentially what happens is a total collision removal(resource names, controller names, helpers, urls) with a minimal effort. I have to admit, I love Ruby on Rails!
Written By:
Haitham Mohammad (e-haitham.blogspot.com)
Comments
Post a Comment
eSpace podcast Prodcast
Archive
- September 2011
- April 2011
- March 2011
- December 2010
- November 2010
- September 2010
- August 2010
- July 2010
- June 2010
- April 2010
- March 2010
- November 2009
- October 2009
- September 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- November 2008
- October 2008
- September 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- January 2008
- April 2007
- March 2007
Latest Comments
- SpectraMind Commented on Egypt Wins UK's National Outsourcing Association Award
- Rofaida Awad Commented on Go Egypt Go!
- Different Mike Commented on Only idiots change their iPhone root password!
- Mike Commented on Only idiots change their iPhone root password!
- smile Commented on Only idiots change their iPhone root password!

