
One extremely nice feature about Ruby is that here-doc terminators may be indented (if the terminator specification begins with a hyphen). This means it is not necessary to either put here-docs at the left margin, or to quote some hardcoded amount of whitespace in the terminator specification (as in Perl). Here-docs can make nice easy templates for simple code generation — but what about whitespace sensitivity of the generated code (such as RDoc markup)?
The following is a simple regex to strip common leading spaces from a multi-line string (added as a method to the String class in this example):
class String
def undent
a = $1 if match(/\A(\s+)(.*\n)(?:\1.*\n)*\z/)
gsub(/^#{a}/,'')
end
alias :dedent :undent
end
And now, if you have some method that returns a here-doc, you can simply dedent it:
class SomeTemplate
def some_meth(foo,bar)
<<-STOP.dedent
* #{foo} list item
* sublist with #{bar} item
STOP
end
end
x = SomeTemplate.new
puts x.some_meth('first', 'second')
__END__
output:
* first list item
* sublist with second item
Not rocket science, but I find it handy to have a dedent method lying around for just such uses.