Written October 3, 2008. Tagged Ruby, Ruby on Rails.
Just came up with a simple but useful Rails trick (though I'm likely not the first).
Say you have a long table with the same controls (buttons, pagination, whatever) both above and below it.
Doing the controls twice over is not DRY; using a helper or partial may be overkill if these controls are never reused other than these two times.
Enter content_for
.
It's commonly used to pass content such as a title or sidebar box from a template to a layout, but you can also use it within one and the same page.
Hence:
<% content_for :controls do %>
<ul>
<li>Do this</li>
<li>Do that</li>
</ul>
<% end %>
<%= yield :controls %>
<table>
…
</table>
<%= yield :controls %>
Prettier in Haml, of course:
- content_for :controls do
%ul
%li Do this
%li Do that
= yield :controls
%table
…
= yield :controls
The effect is something like inline partials. Perfectly DRY without adding much complexity.