如何将yml文件的内容传递到我的erb模板?

Bla*_*man 1 ruby yaml erb

我的yml文件如下所示:

defaults: &defaults
  key1: value1
  key2: value2
  ..
  ..
Run Code Online (Sandbox Code Playgroud)

我的模板文件具有以下内容:

<%= key1 %>
<%= key2 %>
Run Code Online (Sandbox Code Playgroud)

所以我的脚本有一个文件列表,循环遍历它们,我想将yml对象传递给我的erb进行解析:

config = YAML::load(File.open('config.yml'))ENV['ENV']

file_names.each do |fn|

  file = File.new "#{fn}", "r"

  template = ERB.new file

  result = template.result

  # save file here

end
Run Code Online (Sandbox Code Playgroud)

如何将配置对象传递给erb模板系统?

Phi*_*rom 5

http://ciaranm.wordpress.com/2009/03/31/feeding-erb-useful-variables-a-horrible-hack-involving-bindings/的帮助下

不是很漂亮,但是如果您把课程隐藏起来,那就还不错。不利的一面是,您可能会遇到调用ThingsForERB类中不存在的其他方法的问题,因此您需要在config['key1']按照Sergio的建议进行更改之前考虑一下。

require 'erb'

config = {'key1' => 'aaa', 'key2' => 'bbb'}

class ThingsForERB
  def initialize(hash)
    @hash = hash.dup
  end
  def method_missing(meth, *args, &block)
    @hash[meth.to_s]
  end
  def get_binding
    binding
  end
end


template = ERB.new <<-EOF
  The value of key1 is: <%= key1 %>
  The value of key2 is: <%= key2 %>
EOF
puts template.result(ThingsForERB.new(config).get_binding)
Run Code Online (Sandbox Code Playgroud)

运行时,输出为:

  The value of key1 is: aaa
  The value of key2 is: bbb
Run Code Online (Sandbox Code Playgroud)