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?
–
February 8, 2008Very 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.
Vidar
February 8, 2008To 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…
–
February 8, 2008You 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.