Search code examples
ruby-on-railsrubyfixtures

Dynamically generate fixtures in Rails via loop in YAML file


I want to avoid a ton of boilerplate/copying and pasting, and the way the database schema is structured with tables, foreign keys, etc., I ought to be able to do something like this:

#simplified example
<% ["offense", "defense", "special_teams"].map do |position|%>

home_<%=position%>_player:
  game: 1
  team: buckeyes
  player: home_<%=position%>_player #uses fixture label for association
  division: northeast
  season: "2015"
  <%=position%>_stat: home_<%=position%>_stat #uses fixture label for association

away_<%=position%>_player:
  game: 1
  team: hokies
  player: away_<%=position%>_player
  division: southeast
  season: "2015"
  <%=position%>_stat: away_<%=position%>_stat
<% end %>

I've tried loading this in an IRB session to no avail though. The exception was

Psych::SyntaxError: (<unknown>): mapping values are not allowed in this context at line 5 column 26

which makes me wonder if what I'm doing is valid YAML.


Solution

  • It turns out that the above YAML is valid, but that it must be loaded differently than a standard YAML file:

    YAML::load(ERB.new(File.read(PATH_TO_FILE)).result)
    

    I discovered the proper loading logic in "YAML with erb is not parsing", but wanted to add this answer since I couldn't find any examples that used a looping mechanism other than for and that interpolated to this extent.