Proper RHTML tags for each loops

Last night and this morning I have wasted few hours trying to move forward, over some stupid issue. I was parsing XML data with Hpricot, and since it was my first approach to problem, I was just dumping to output some fields from XML data. And here my frustration began.

Since output from my views was parsed by third party application, I got error messages about unknown HTML tags in my output. View in my app was pretty straightforward. Take XML data, parse it with Hpricot, search for specific fields (UIDs in this case) and those numeric UID should be displayed. However every time in my output were XML tags not just UIDs (<uid>SOME_NUMBER</uid> and I was expecting just SOME_NUMBER)

How I was doing this?

<% xml = Hpricot.parse(@chunk_of_xml_data)
data = (xml/:uid) %>
<%= data.each { |u| u.innerHTML  } %>

Well I was just wrong ;-) using <%= in each loop results in following ERB parser behavior: it dumps all output from inside code block { } and puts in output last result. It happens that after running data.each Ruby will return data itself, and this was part of XML data, matching search pattern ((xml/:uid)). As result was as I wrote (series of <uid>SOME_NUMBER</uid>).

So, remember, when iterating through some collection with each put iteration code in non-output RHTML tags (<% %>)

Working code in my example should be something like this:

<%
xml = Hpricot.parse(@chunk_of_xml_data)
data = (xml/:uid) %>
<% data.each { |u| %>
<%= u.innerHTML  %>
<% } %>

Difference is that data.each is non output RHTML tags, only UID value output is put inside <%= %>. This is quite obvious when You look at this, but it took me some time to spot this #$%^ equal sign ;-))

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.