Blankman
Blankman

Reputation: 266940

How to pass contents of a yml file to my erb template?

My yml file looks like:

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

My template files have the following:

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

So my script has a list of files, loops through them and I want to pass the yml object to my erb for parsing:

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

How do I pass my config object to the erb templating system?

Upvotes: 1

Views: 3005

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

With help from http://ciaranm.wordpress.com/2009/03/31/feeding-erb-useful-variables-a-horrible-hack-involving-bindings/

Not super pretty, but if you hid the class away then it's not so bad. Downside is you'll probably run into problems calling other methods that don't exist in the ThingsForERB class so you'll want to think about that before just changing things over to use config['key1'] as Sergio suggested.

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)

When run the output is:

  The value of key1 is: aaa
  The value of key2 is: bbb

Upvotes: 5

Related Questions