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.
