Change in behavior with Ruby comments in ERB

I ran into an interesting problem while working on a Rails project. The website was rendering incorrectly on my home machine but was fine on the server. After an hour or so of going through the code I finally got wise and used wget to download the pages and diff to find the differences. This proved effective as I found the section on html not being rendered. Of course, that didn’t answer why that section wasn’t being rendered. I finally found it was related to the fact that there was a comment in the code above it. Here are the details.

Basically I had something that looked like this:

<% end # some comment %>
</td></tr></table>
<% if true %>

As far as I can tell some recent change to my system caused the ERB to parse the closing delimiter as part of the comment. This code has worked for some time, and was working on the server. As best I can tell it was either an upgrade for Ruby or an upgrade for Rails that caused the change. I’m a little disappointed as this is a convenient syntax to use. I have experimented with a few alternatives though none that I’m completely satisfied with. The best so far (as it’s been the only one tha remains on one line) has been:

<% end; 'some comment' %>

That changes the return value of the code but so far I haven’t noticed that to be a problem. I’m not sure I have the time to really dig into this but it is worth noting.

Trackback URL for this post:

http://hightechsorcery.com/trackback/200

1.8.7-compatible ERB comment syntax

Just struggled with this after upgrading to Ruby 1.8.7 and Rails 2.2.2.

Here is a relevant portion from the inline documentation for ERB:

| ERB recognizes certain tags in the provided template and converts them based on the rules below:
|
| <% Ruby code -- inline with output %>
| <%= Ruby expression -- replace with result %>
| <%# comment -- ignored -- useful in testing %>
| % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
| %% replaced with % if first thing on a line and % processing is used
| <%% or %%> -- replace with <% or %> respectively

So, contrary to some suggestions (http://www.ruby-forum.com/topic/154835#693739), comments ARE allowed in ERB, but it seems to be safe only to do so when the whole embedded expression is a comment, i.e.:

<%# this is good comment %>

<% n=1 # this is a bad comment %>

If your 'bad comments' are consistent in their usage of whitespace around the hash mark, then it ought to be easy to do a grep search-and-replace to change all your bad comments to look like this, which WILL work in Ruby 1.8.7:

<% n=1 %><%# this is the fixed comment %>

Creative Commons License Except where otherwise noted, content on this site is licensed under a Creative Commons by-nc-sa 3.0 License