To ERB or not to ERB — that is the question…

ERB vs. Haml

During my adventures in Ruby and now Sinatra, I’ve grown accustomed to writing the code a certain way. Being a newbie, I just assumed that there was only one way to write the code. Well, we all know what happens when you assume…

Sinatra introduced me to ERB files, or Embedded Ruby, which are a hybrid of HTML and Ruby. Take, for example, my most recent Sinatra project as part of the Learn curriculum. Here is some code for a user to sign up for my app:

<div class=”container”>
<% if flash[:message] != nil %>
<h2><small> <%= flash[:message] %> </small></h2>
<% end %>
<h1>Welcome <%= current_user.username %> !</h1>
<h2>Your Instruments:</h2>
<h2><small>Click on an instrument to view and/or edit its information.</small></h2>
<% @instruments.each do |instrument| %>
<h3><small><li><a href=”instruments/<>”><%= %></a></li></small></h3>
<% end %>
<a href=”/new” class=”btn btn-success” role=”button”><span class=”glyphicon glyphicon-file”></span> New Instrument</a>
<a href=”/logout” class=”btn btn-warning” role=”button”><span class=”glyphicon glyphicon-log-out”></span> Log Out</a>

Pretty straightforward, right? That’s what I thought to. In ERB files, you code HTML as normal. When you want to include Ruby, you have 2 options: the substitution (<%=…%>) or the scripting (<%…%>) tag. Substitution tags evaluates the enclosed Ruby code and displays the results. On the other hand, scripting tags simply evaluate Ruby code, but do not display the result.

Now, as I was googling some concepts, I came across Haml (HTML Abstraction Markup Language). This language is supposed to facilitate faster coding by making it cleaner and more readable. I found a converter online (you can find anything if you look hard enough!), and here is a snippet of the same code I showed you above, but now written in Haml:

— if flash[:message] != nil
= flash[:message]
Welcome #{current_user.username} !
%h2 Your Instruments:
%small Click on an instrument to view and/or edit its information.
— @instruments.each do |instrument|
%a{:href => “instruments/#{}”}=
%a.btn.btn-success{:href => “/new”, :role => “button”}
New Instrument
%a.btn.btn-warning{:href => “/logout”, :role => “button”}
Log Out

WOW, talk about a difference. Is it cleaner…readable? Perhaps.

In conclusion, Haml definitely deserves a closer look in the future.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.