I’ve been spending a good amount of time lately with Ruby on Rails partials. If you’re not familiar with the concept of a partial they’re similar to include files, but seem a lot more powerful. A partial allows developers to easily reuse code in multiple places. A perfect example would be a list of most recent blog posts. Partials enable this code to be easily integrated into every page of the application without having to worry about repeating it. If you’re familiar with ColdFusion, then partials are very similar to using the cfinclude tag. Having code that is modularized into partials and components makes development a less daunting task.
I wanted to take a minute and write about dual purpose partials. I say “dual purpose” because this was the first time I ran into the scenario I’m about to describe. Prior to this most of my partials where fairly static, which means I didn’t have a need for using this technique. I’ll start by showing you the basic code to render a partial:
<%= render(:partial => “notesrow”, :collection => @notes) %>
This assumes a partial with a file name of _notesrow.rhtml that resides within the current views directory. The name of the partial is notesrow and I created an instance variable called @notes. This variable is passed as a collection to the partial where it will then be automatically enumerated.
Now the interesting part is that within this partial there’s a local variable called notesrow which contains a notes object. One notes object for each iteration of the loop. Therefore the partial code would look something like:
[div]
The subject of this note is <%= notesrow.subject %>
The description of this note is <%= notesrow.description %>
[/div]
This code is enumerated until there are no more notes records. Therefore the notesrow partial has two purposes:
1. Assign a partial called notesrow that links to the file _notesrow.rhtml
2. Creates a local variable called notesrow that contains the current notes object
Partials also make it very easy to do Ajaxy things with your applications. Not to say that you can’t do it without partials, but they simplify the code you have to manage for a given task. For more information about RoR partials feel free to check out the following book: