Many languages have a decent way to assign or output multiple lines of text without actually making you concatenate a bunch of strings and newlines. They’re usually called “here documents” or heredocs, and in Ruby, it works line this:
expected = <<EXPECTED
<object width="500" height="411">
<param name="wmode" value="transparent"></param>
wmode="transparent" width="500" height="411"></embed>
</object>
EXPECTED
(That’s from a test I was working on involving modifying an embed, but I took the long lines out for formatting reasons. I’m not sure it’s the best approach to testing, but at least there was a test – thanks, autotest!)
In the above case, I’m saying “assign this string, and keep going until you see the EXPECTED symbol. I could also have used “expected = <<-EXPECTED” and the dash would have told Ruby that I want to indent the closing token. You know, for looks.
But wait! That code has a bug! True story – it won’t run as I’ve typed it here, even though it looks totally valid.
The closing token can’t have any trailing whitespace.
If it does, you’ll get a “can’t find string ‘EXPECTED’ anywhere before EOF (SyntaxError)” error. And of course most editors aren’t set up to show invisible tokens, so you might find yourself wailing and gnashing your teeth if you haven’t run into this error before (I blog about my simple errors often, and I know they make me look a little dense at times, but it helps ensure I won’t do it again, and hopefully someone else who doesn’t have the benefit of a peer review will find it and save some time as well.)
After (finally!) figuring out why my code wasn’t working, I checked to see if the code would work if the trailing spaces matched on the setup and closing tokens – i.e. if there were two spaces after both instances of “EXPECTED” – but then you get a different error about how the first line didn’t end like it was supposed to.
Interestingly, in BBEdit, which is my editor of choice, the syntax colouring gets all screwed up when there are spaces, because BBEdit knows how heredocs are supposed to work even if you don’t, so there’s a clue too.
Ruby also has some features involving multiple heredocs starting on the same line, and some fun stuff with quotes around the tokens, but this isn’t the definitive Ruby heredoc post, just a “get out of heredoc whitespace hell” post that might prove useful to some of you.
{ 0 comments }

