YAML with erb is not parsing

kirlev picture kirlev · Aug 4, 2014 · Viewed 9.7k times · Source

Why this yaml file won't parse?

---
<% sensor_types = YAML.load_file('db/seed-fixtures/sensor_type.yml') %>
<% sensor_types.each do |sensor_type| %>
sensor<%= sensor_type['id'] %>:
  id: <%= sensor_type['id'] %>
  title: <%= sensor_type['title'] %>
  unit: "<%= sensor_type['unit'] %>"
  valid_min: <%= sensor_type['valid_min'] %>
  valid_max: <%= sensor_type['valid_max'] %>
  codename: <%= sensor_type['codename'] %>
  scale_base_ten_exponent: <%= sensor_type['scale_base_ten_exponent'] %>
<% end %>

this file is used for fixtures in my tests, it is loaded by rspec from the fixtures directory.

when I try it I get: "mapping values are not allowed in this context at line 4 column 28 (Psych::SyntaxError)"

Answer

Dimitri picture Dimitri · Aug 4, 2014

You can't load a YAML file containing ERB like a basic YAML file. Checkout this post.

What you can do instead is (in a spec initializer or a before hook):

FIXTURE_CONFIG = YAML.load(ERB.new(File.read("#{Rails.root}/path_to_your_file.yml.erb")).result)

And then use this variable in your test.