Fun With Here Documents

Today I was fixing up some inefficiencies in Rail’s Postgresql adapter (more about that in a later post), and came across this strange looking code:

def tables(name = nil)
  schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
  query(<<-SQL, name).map { |row| row[0] }
        SELECT tablename
        FROM pg_tables
        WHERE schemaname IN (#{schemas})
        SQL
end

The code is passing a here document, which is basically a long string, as a parameter to the query method. The here document is demarked by the string “SQL.”

What took me by surprise is the here document is defined after the method call, which is a code construct I’ve never seen before. Making sure my memory wasn’t failing me, I double checked my copy of The Pick Axe book and verified it never mentions this feature.

Hats off to Jamis, who added this neat little trick to Rails in revision 2317, way back in September 2005, and to Anthony who blogged about it last month. And finally, the Ruby Wikibook has a great tutorial about here documents. Who knew that you can have multiple here document parameters per method call?

Leave a Reply

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

Top