How do I comment out code in my views?

You’ve been writing a view — it’s got quite a bit of code in there and you need to play around with a few bits and pieces. So it’s time to comment a chunk of the code out so you can adjust the layout.

First try — let’s use some HTML comments <! — IGNORE ME →. And that works great for your markup — but your Ruby still gets executed.

How do you comment out lines in ERB?

Well the simplest is to use an ERB comment. Instead of <%= @person.name %> you can use <%# @person.name %> and your Ruby code is ignored.

But that only works for single lines.

There must be a way to do this for multiple lines … it’s just not immediately obvious.

Ruby has a block comment syntax that looks a bit weird:

=begin
This is a comment
=end

And you can use that in your ERB template:

<% 
=begin
%>
<%= @person.name %>
<%
=end
%>

I told you. Weird eh?

You definitely don’t want that all over your code.

However, there’s another little trick you can use that is technically weird but works great.

In your application_helper.rb define a new method:

def ignore
# do nothing
end

Then in your views you can use it like so:

<% ignore do %>
<%= @person.name %>
<% end %>

Your view is now calling this “ignore” method and passing it the block which has the code you want to ignore. Normally a helper method returns some content that gets rendered into your template — whether that content comes from parameters or by manipulating a block.

But your ignore method does nothing. So the block is ignored and your view is code-free.

[mc4wp_form id=”427"]