Hi! Thanks for visiting my blog. If you've received any value from my content would you mind supporting my new startup by downloading our browser add-on? It's called PriceBlink and makes online shopping a breeze. You can watch it in action here and download it for Chrome, Firefox, IE, or Safari by going to PriceBlink.com. Thank you and I hope you enjoy!

Suppressing Whitespace with Ruby on Rails

Feb 15

Whitespace is a pet peeve of mine. It doesn’t cause much harm although it can make debugging code a bit difficult. Plus it can add to overall size bloat of your webpage. Back in the ColdFusion days I used to use techniques such as cfsetting and cfprocessingdirective to remove whitespace.

I was excited to see that the Ruby on Rails team took this into consideration and made it simple to suppress whitespace in certain circumstances. Take the following code for example:

<% 5.times do %>
Your IP Address is: <%= @request.remote_ip %>
<% end %>

When this template is rendered in the browser and the source is viewed you’ll see:

our IP Address is: 127.0.0.1<br />

Your IP Address is: 127.0.0.1<br />

Your IP Address is: 127.0.0.1<br />

Your IP Address is: 127.0.0.1<br />

Your IP Address is: 127.0.0.1<br />

Now let’s use a nifty RoR trick to remove the whitespace:

<% 10.times do -%>
Your IP Address is: <%= @request.remote_ip %>
<% end -%>

Notice the minus sign at the end of the first and last line which yields the following output:

Your IP Address is: 127.0.0.1<br />
Your IP Address is: 127.0.0.1<br />
Your IP Address is: 127.0.0.1<br />
Your IP Address is: 127.0.0.1<br />
Your IP Address is: 127.0.0.1<br />

Notice the clean output. While it seems trivial it keeps guys like me happy.

Leave a Reply