1

私のymlファイルは次のようになります:

defaults: &defaults
  key1: value1
  key2: value2
  ..
  ..

私のテンプレートファイルには次のものがあります:

<%= key1 %>
<%= key2 %>

したがって、私のスクリプトにはファイルのリストがあり、それらをループし、解析のために 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

構成オブジェクトを erb テンプレート システムに渡すにはどうすればよいですか?

4

1 に答える 1

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)

実行すると、出力は次のようになります。

  The value of key1 is: aaa
  The value of key2 is: bbb
于 2012-11-17T18:21:48.910 に答える