Fun With Here Documents

Posted by Charlie Thu, 07 Feb 2008 21:07:00 GMT

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?

Posted in  | 3 comments | no trackbacks

Comments

  1. Avatar Ermar said about 3 hours later:

    Very good tutorial! It’s fantastic and interesting. I learned a lot of things in different programming languages and environments. Thank you for the knowledge you’ve shared.

  2. Avatar Vidar said about 15 hours later:

    To me it’s probably one of the biggest warts in Ruby, but then I’m a language purist and heredoc’s are one of the things that really make it nasty to formally specify Ruby’s grammar…

  3. Avatar Ronald said about 16 hours later:

    You must be very efficient with coding. I have been trying to debug myself but it takes me quite some time. I will copy your codes, thanks.

Trackbacks

Use the following link to trackback from your own site:
http://cfis.savagexi.com/trackbacks?article_id=fun-with-here-documents&day=07&month=02&year=2008

(leave url/email »)

   Comment Markup Help Preview comment