require 'erb'
File.open('./test.txt', 'w+') do |f|
name='Darcy'
erb = ERB.new(File.new('template').read)
f.write(erb.result(binding))
end
My template file was a single line that contained this: "Hello <%=name%>". I think you can probably figure out what the result would look like ;-)
The real example he used in his presentation was slightly more elaborate in that he had a source of data, an XML file, and he used REXML (a great XML library in Ruby) to read the source to generate a SQL file.
I'm not a big advocate of code generation but if you find yourself in the unenviable position of needing to do it then this is a great place to sprinkle in a little Ruby magic.
No comments:
Post a Comment