我们使用这个ruby脚本从erb template + json配置文件中呈现我们的配置文件。它基本上来自http://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html
的示例最近我们不小心从json中删除了一些东西,而我们仍然在erb文件中引用它。该脚本有效,只需用空字符串替换占位符即可。有没有办法让它失败?
在下面的例子中
$ render.rb conf.json template2.erb out2 ; echo $?
将失败,因为缺少一个完整的块,但是如果只缺少一些键值对,则它不会发出警告或失败:
$ render.rb conf.json template1.erb out1 ; echo $?
将以0
退出conf.json:
{
"block1" : {
"param1": "p1"
}
}
template1.erb:
foo=<%= @config['block1']['param1'] %>:<%= @config['block1']['missing_param'] %>
template2.erb:
foo=<%= @config['block1']['param1'] %>:<%= @config['block1']['missing_param'] %>/<%= @config['missing_block']['anything'] %>
render.rb:
#!/usr/bin/env ruby
# usage: conf_gen.rb config_file.json erb_template output_file
require 'erb'
require 'json'
require 'pathname'
class MyRenderer
def initialize(config_path)
@config = JSON.parse(File.read(config_path))
end
end
if ARGV.size != 3
puts "Hey, missing arguments.\nUsage: conf_gen.rb <json config file> <erb template> <output file>"
exit
end
config_path = ARGV.shift
template_filename = ARGV.shift
output_file = ARGV.shift
erb = ERB.new(File.read(template_filename))
erb.filename = template_filename
ConfigRenderer = erb.def_class(MyRenderer, 'render()')
output = File.new(output_file, 'w')
output.puts(ConfigRenderer.new(config_path).render())
output.close
puts "Finished Successfully"