Continuing with my exploration of Ruby on Rails as a .NET guy, here’s an awesome example of Convention over Configuration at work. I decided to add bite size snippets of some of the cool things I encountered in Ruby and Rails. If you are interested in more, see my other Ruby posts.
Today’s post illustrates how elegantly the render partial helper method in Rails works. Assuming you’ve done some MVC development, you should be very familiar with a partial view. Partials are used to keep your view nice and clean. When things start getting complex within a view, you may want to think about adding a partial.
Take for example a library or bookstore application. One of the models in the application is, of course, a book. The books are displayed in a list as well as individually on a details page. During the course of development, you notice that you have quite a bit of repeated code between the index and show pages. This is a good opportunity to use a partial to DRY up your code. You take the repeated book view code (which I won’t post here since it doesn’t matter what it is), and put it into a partial (_book.html.erb). Within the partial we are referencing a local object simply called book.
Single Partial
On your detail page (a single book), it’s a simple replacement like so:
<%= render :partial => "book", :object => @book %>
But even better, since our partial is named the same as our model, we can shorten up the syntax:
<%= render :partial => @book %>
Now that’s some convention goodness right there.
More...