03.11.07
New Plugin: current_resource
by Chris Abad
One of the nice things about Ruby on Rails is it’s use of convention over configuration. The idea is that if you follow common conventions, everything just kind of falls into place for you. We adopted many RESTful conventions a while ago, and have been reaping the benefits ever since. However, one thing we, and many others, have noticed with our shiny new RES Tful-style controllers is that they begin to look a little repetitive. This leaves us with a great opportunity to begin extracting these repetitive bits to help DRY up our code.
CurrentResource is a Ruby on Rails plugin which creates some nice convenience methods to access the current resource being referenced in the request URI when you follow common RES Tful conventions.
So What’s It Do?
Let’s get the basics out of the way first. Make sure you install the plugin and restart your application:
./script/plugin install http://svn.integralserver.com/plugins/current_resource
The easiest way to explain this is with an example. Let’s use the ever-so-popular example of a blog:
# URI: /articles/1 current_article #=> Article.find(1)
What About Nested Resources?
The main reason why I wrote this plugin was to create an easy way to access the parent resource being referenced with nested resources. This is what I mean:
# Nested route in config/routes.rb map.resources :articles do |article| article.resources :comments end # URI: /articles/2/comments/1 current_article #=> Article.find(2) current_comment #=> Comment.find(1)
Use of method_missing
One important item to note is that CurrentResource utilizes method_missing to dynamically add the current_resource method. What this means is that if methods with this format already exist, those will take precedence. For example, if you have a current_user method defined as part of your authentication system, that is the method that will called.
If you liked this article, feel free to digg it
Comments
There are no comments.
Leave a Comment