DRYing up our views with Rails 2

DRYing up our views with Rails 2By 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.

Leave a Reply




About Bemba Media

Bemba Media is a new social media company based in Amsterdam, the Netherlands. Founders Aaron Peters and Arne Dibbits are on a mission to offer people the easiest way to share their web experiences with friends and to discover what’s hot on the web right now.

The company launched Bemba.com in March 2008.

Bemba users share their favorite videos and websites on the social platforms they already use with their friends, like Facebook, Twitter and Hyves. More social networks and (micro-) blogs will follow.

Bemba will become a destination for 'funsurfing' the web, providing easy access to web content that people with similar interests have recently recommended to their friends.

Flickr photos

meeting with Sanoma NL in Hoofddorp #

Bemba blog in Wordle

More Photos

Twitter updates

    Recent readers