bluejimmy bluejimmy - 3 months ago 9
Ruby Question

What does f.write << TEMPLATE mean in the below code snippet

File.open("db/quotes/#{id}.json", "w") do |f|
f.write <<TEMPLATE
{
"submitter": "{hash["submitter"]}",
"quote": "{hash["quote"]}",
"attribution": "{hash["attribution"]}"
}
TEMPLATE
end


I understand what this method is doing. I read this code snippet out of a book. It is trying to write to a json to a file with whatever name #{id}.json is. I have never seen it before. Is "<<" an operator? What is "TEMPLATE"? Btw, this it out of the book rebuilding ruby on rails. In the section of rebuilding the Model layer is where i found the code snippet. It could have something to do with the Gem "erubis".

Answer

f.write expects a string as an argument and writes that string to the file f.

<<TEMPLATE starts a string that ends at the next occurrence of TEMPLATE. This kind of strings are called heredocs.