1、编写erb模板
template/sql.erb
<%for organization in data.keys%>insert into org_domain(Domain, organization) values('<%=data[organization]%>','<%=organizatio
n%>');
<%end%>
2、稍微复杂一些的生成器代码
create.rb
#!/usr/bin/env ruby
require "erb"
require 'json'
class Creater
def proc
str = IO.read("config.json");
configs=JSON.parse(str)
configs.each do |p|
create(p)
end
end
def create(p)
Dir.mkdir("dist") unless FileTest.exist?("dist")
todir = "dist/" +p["name"]
Dir.mkdir(todir) unless FileTest.exist?(todir)
Dir.foreach("template") do |file|
if file !="." and file !=".."
data = p["data"]
tofile =File.new(todir+"/"+file, "w")
fromfile = "template/"+file
File.open( fromfile ) { |fh|
e = ERB.new( fh.read )
tofile.print e.result( binding )
}
tofile.close
end
end
end
end
c = Creater.new()
c.proc()
config.json
[{"name":"a","data":{"a":"a","b":"b"}},
{"name":"b","data":{"b":"a","b":"b"}},
{"name":"c","data":{"c":"a","b":"b"}},
{"name":"d","data":{"d":"a","b":"b"}}]
5、执行 ruby creater.rb
在dist下生成4组代码,后续增加模板,可以实现代码的快速生成。