Clear, usable interfaces. Clean, accessible code.

Route 19

Logbook.

Ruby HTML Indentation Jun. 27 at 9:47 am

I’ve very particular about the html I write. On top of writing to a strict doctype, keeping tags semantic and limiting the number of divs and classes, I also like to ensure the html is easy to read and looks great. Part of this is formatting indents to make nested elements easier to follow.

Unfortunately when I’m dealing with dynamic content those indents are often out of my control. Typically this will happen in a Rails project when running content through textilize. My solution was to add a very simple String method to add tabs to the beginning of each line.

class String # adds tabs to the beginning of each line def indent(tabs=3) self.gsub(/^/, "\t"*tabs) end end

Now anytime I want to ensure proper indentation, I just call my indent method on the string, and I can even pass the number of tabs to use (defaults to 3):

<div class="section"> <div class="article"> <%= textilize(@article.body).indent %> </div><!-- // article --> </div><!-- // section -->

The above would output something like this:

<div class="section"> <div class="article"> <p>A formatted line.</p> <p>Another formatted line.</p> <p>Etcetera.</p> </div><!-- // article --> </div><!-- // section -->

Ruby is awesome. Regular expressions are certainly not my strong suit, so there may very well be a better way to gsub the tabs, but this is working well in my limited tests.

Recent Entries

More