Storing YAML in YAML Fixtures

written by nap on January 10th, 2008 @ 05:33 PM

If you ever find yourself in a situation where you have an attribute value that needs to be serialized (stored as YAML) and used within a (YAML) fixture, you can do something like:

FancyWidget:
  id: 1
  name: FancyWidget
  serialized_hash: "<%= {:abc => {:xyz => 'foo'}}.to_yaml %>"

Or, if you want to embed YAML directly you can do:

FancyWidget:
  id: 1
  name: FancyWidget
  serialized_hash: |
    ---
    :abc: 
      :xyz: foo

This is probably old hat to a lot of you, but I figured I'd doc it here since the solution felt somewhat non-obvious at first. Rails stores serialized attributes in your database this way, so you might run into this if you're using ActiveRecord's serialize method.

Comments

  • Justin Blake on 18 Jan 16:48

    You figured it out! Quotes! Genius!

  • nap on 19 Jan 12:20

    No kidding, right? And still, it took me 30 minutes of struggling to get it. Hah!

Post a comment