Hiding Code

- - posted in ruby | Comments

Commenting out large chunks of code in Erb templates is sometimes a bit tricky, time consuming and looks ugly even with an IDE like Netbeans.

For example:

1
2
3
4
5
6
7
8
<% if @document.fresh? %>
  <div class="fresh document"><%= link_to @document.title, @document %></div>
<% end %>
becomes:

<%# if @document.fresh? %>
  <%#*<div class="document fresh">%><br>    <%#= link_to @document.title, @document %><br>  <%#*</div>%>
<%# end %>

or

1
2
3
4
5
<%# if @document.fresh? %>
<!-- <div class='document fresh'> -->
  <%#= link_to @document.title, @document %>
<!-- </div> -->
<%# end %>

Only a few lines and not very plesent to read.

A better way to comment out code in Erb?

The key is not to use comments:

1
2
3
4
5
<% hide do %>
  <% if @document.fresh? %>
    <div class="document fresh"><%= link_to @document.title, @document %></div>
  <% end %>
<% end %>

And the implimentation of hide is super simple:

application_helper.rb

1
2
3
def hide(&block)
  # do not yield
end

We accept the block but don’t yield it. Could this be the simplest DSL implimentaion ever?

Maybe DSL is pushing it, but still…

Comments