开发者

why is #comment syntax not allowed in erb's <%= %>?

I'm 开发者_运维百科using Ruby on Rails 3. I had tried to add #comment in <%= %>, and it turned out that it's not valid...and error raised... My code is:

<%= @page_title || 'Pragmatic Bookshelf' #magic @page_title; a if a is true, else b%>

It seems ok putting #comment into <% %> without the equal sign in it. My question is: why is that?

Also, how do you put comment inside <%= %>?

Thanks.


A #comment runs to the end of a line, but the use of = is rewritten as a function call, like puts()

If we rewrite

<%= @page_title || 'Pragmatic Bookshelf' #magic @page_title; a if a is true, else b%>

as

puts(@page_title || 'Pragmatic Bookshelf' #magic @page_title; a if a is true, else b)

It becomes clear that the closing parenthesis ) is part of the comment, and therefore the statement can't be parsed correctly.

To work around this, we can just use a separate ERB comment block, like so:

<%= @page_title || 'Pragmatic Bookshelf' %><%# magic @page_title; a if a is true, else b%>

As a final note, using the || operator to coalesce nil variables is a very common Ruby idiom, and does not need a comment at all. As Steve McConnell says in Code Complete, comments should explain why something is done, not how something is done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜