By necessity, our views contain lots of repetition. We have “content boxes” with rounded corners. By virtue of MSIE, these boxes are actually boxes inside boxes inside boxes. An example.
This code demonstrates it pretty well:
<div class="box">
<div class="top"></div>
<div class="content">
<p>Content goes here</p>
<!-- /content --></div>
<div class="bot"></div>
<!-- /.box --></div>
With multiple content boxes per page, there’s lots of identical divs in a template. And consequently, lots of room to DRY things up.
To accomplish this I am using a cool feature of Rails 2: partials with layouts.
It does what is says on the box: a partial is wrapped inside a layout. This layout is the repeating part (all the divs in the code above) and the <%= yield %> inside the layout renders the stuff inside the content box (the unique stuff).
The view code now looks like this:
<% render :layout => 'shared/content_box' do %> <p>Content goes here</p>
<% end %>
Quite an improvement, especially when you multiply by 20.
Side-effects of these refactorings are that you gain a more ‘birds-eye’ view of the code and new possibilities for optimizations come up. Stuff you were unable to spot previously.

Subscribe to our RSS feed


1 Response to “DRYing up our views with Rails 2”