yet another crazy proposal from me.. read on, am I crazy?
motivation
==========
I use heredocs for small templates, ala
class HTML
# ...
def write_page(body, title, css, filename)
html = <<EOHTML
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head><title>#{title}</title>
<style type="text/css">#{css}</style></head>
<body>#{body}</body></html>
EOHTML
File.open(filename, "w+") {|f| f.write(html) }
end
# ...
end # class HTML
Its disturbing to have many such heredocs which breaks indendation
completely. The problem with '<<-EOHTML' is that you get the indention
from your source into the output. To circumvent this I often make use of
<<-EOHTML.gsub(/^\s*/, "") which removes that indentation, however the
interpolated text gets also gsub'ed which Im not interested in.
I could do eval of <<'EOHTML'.gsub(/^\s*/, ""), but then the simple idea
turns into a long beast, which confuses more that it helps. Then it
probably better to use doublequotes than heredoc.
proposal
========
If we somehow could manipulate the text string before interpolation
occured. For instance by executing code on the HereDoc end tag.
server> ruby a.rb
a.rb:10: can't find string "EOF" anywhere before EOF
a.rb:3: syntax error
server> expand -t2 a.rb
def m
inline = "1\n space\n3"
text = <<-EOF
pre
#{inline}
post
EOF.gsub(/^\s*/, '')
text
end
p m
server>
Tell me is this a bad idea?
--
Simon Strandgaard