Example 2-7 works
perfectly well, but experienced Rails developers will look
at it and wonder why we typed so much. Why? The parentheses around the
arguments to h()
are (usually)
optional. You can produce the same result with the version shown in
Example 2-8.
Example 2-8. Escaping instance variables without using the parentheses
<html> <head><title><%=h
@message %> </title></head> <body> <h1><%=h
@message %></h1> <p>This is a greeting from app/views/hello/index.html.erb</p> <p><%=h
@bonus %></p> </body> </html>
A lot of developers just think of <%=h
as the opening to escaped content, and
when you’re just dropping an instance variable into the content, this
works beautifully.
It doesn’t work, however, when Ruby needs to know where the parentheses are for more complex or ambiguous expressions, such as:
<%=h if @foo.length > 1 then "Sausages" else "Mash" end %>
which will produce the unwanted and mysterious:
>> "syntax error, unexpected kTHEN, expecting $end"
You’ll have to choose for yourself which approach is easiest for you—the idiomatic Ruby approach or the safer but more cluttered approach of making parentheses explicit.