back

2 Tips for Rails view formatting

I missed Chad Fowler’s post on Rails pet peeves, but view code that doesn’t know how to use whitespace is one of my biggest Rails pet peeves.

Here’s what I mean:

1
2
3
4
5

<p><strong><%= really_long_helper_method @cat.weight %></strong> was added to your <%= @cat.weight_list_type.titleize %> count.
<% if @cat.happy? %>You ate <strong><%= really_long_helper_method(@cat.eaten_before - @cat.eaten_after) %></strong> by using special <strong><%= @cat.food_type %></strong>!<% end %>
</p>

When an entire page is formatted like that, it turns into this huge pulsating wall of code that’s horrid to work with.

Here’s what I do when I have to work with code like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<p>

  <strong>
    <%= really_long_helper_method @cat.weight %>
  </strong> 

  was added to your <%= @cat.weight_list_type.titleize %> count.

  <% if @cat.happy? %>

    You ate 

    <strong>
      <%= really_long_helper_method(@cat.eaten_before - @cat.eaten_after) %>
    </strong> 

    by using special

    <strong>
      <%= @cat.food_type %>
    </strong>!

  <% end %>

</p>

While I might tighten it up later, it’s so much easier to work with code that you can actually see the structure of.

Here’s another example of formatting that disturbs me:

1
2
3
4

        <p> <%= cat.label :weight, nil, :class => "cat_label" %> <%= cat.text_field :age %></p>
        <p><%= cat.label :name, 'Last Name of Cat for Posterity', :class => "cat_label" %> <%= cat.text_field :cat_name %></p>

Running into forms done like this is a pain, because not only do they wrap, but it takes longer to read through.

And here’s how I would do it (aside from using a form builder…):

1
2
3
4
5
6
7
8
9
10
11

<p> 
  <%= cat.label :weight, nil, :class => "cat_label" %> 
  <%= cat.text_field :age %>
</p>

<p>
  <%= cat.label :name, 'Last Name of Cat for Posterity', :class => "cat_label" %>
  <%= cat.text_field :cat_name %>
</p>

So, here are the rules:

1) Only do one thing on each line. That way it’s immediately clear what the line does.

2) Separate groups, so that 1 line represents a slight change in what the code does, and two lines represent a change in focus. For example, one line between fields in a form and two lines between divs.

April 03, 2009