2

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
aceofbassgreg
  • 3,837
  • 2
  • 32
  • 42
  • use `each` instead of `map` ;-) – MrYoshiji Sep 14 '15 at 21:28
  • 1
    If you haven't read the YAML specification, YAML supports ["Anchors" and "Aliases"](http://www.yaml.org/spec/1.2/spec.html#id2765878), which make it easy to create small boilerplate, then access them later in the document to build up more and more complex structures, similar to macros. So, chunks of what you're doing could probably be DRY'd, such as the common key/value pairs. It's good to know those exist. It's also possible to create YAML in pure Ruby and have it emit the data, rather than use ERB templates. – the Tin Man Sep 14 '15 at 21:49
  • @the Tin Man: Is it possible to access an anchor across multiple YAML files? Referencing the anchor from another fixture file results in an exception, and I've been trying to load the file that has the alias, but still end up with the exception `Psych::BadAlias: Unknown alias: buckeyes` (I've been loading with `<% YAML::load File.read('test/fixtures/cfb/teams.yml') %>`) – aceofbassgreg Sep 15 '15 at 19:39
  • For now what I'm doing is creating a module w/ the reusable data structures and then I'm mixing it in via `ActiveRecord::FixtureSet.context_class.send :include, HelperModule` so that I can access the data in each fixture file. – aceofbassgreg Sep 15 '15 at 20:40
  • That sounds like it'd work – the Tin Man Sep 15 '15 at 22:29

1 Answers1

2

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.

Community
  • 1
  • 1
aceofbassgreg
  • 3,837
  • 2
  • 32
  • 42