ruby 带有erb的YAML不解析

1mrurvl1  于 2024-01-07  发布在  Ruby
关注(0)|答案(1)|浏览(141)

为什么这个yaml文件无法解析?

---
<% 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 %>

字符串
这个文件用于我的测试中的fixture,它是由rspec从fixture目录中加载的。
当我尝试它时,我得到:“mapping values are not allowed in this context at line 4 column 28(Psych::SyntaxError)”

j5fpnvbx

j5fpnvbx1#

你不能像加载基本的YAML文件那样加载包含ERB的YAML文件。检查这个post
你可以做的是(在spec初始化器或before钩子中):

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

字符串
然后在测试中使用这个变量。

相关问题