zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Storing YAML in YAML Fixtures

January 10, 2008 @ 05:33 PM by nap · 6 comments

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.

6 comments so far ↓

  • Justin Blake // January 18, 2008 @ 04:48 PM

    You figured it out! Quotes! Genius!

  • nap // January 19, 2008 @ 12:20 PM

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

  • Aamer // November 15, 2008 @ 01:02 AM

    Nice trick, but unfortunately doesn't seem work well with serializing arrays.

  • Niklas // December 30, 2008 @ 12:28 PM

    For arrays, simply do:

    FancyWidget: id: 1 name: FancyWidget serialized_array: [ one, other ]

  • TheKeeper // March 10, 2009 @ 12:56 AM

    "<%= %w[one two three four five].to_yaml %>"

    Works great - nice tip

  • Jason King // July 05, 2009 @ 12:50 PM

    Just a tip, when .to_yaml actually needs to quote a string, then it will use double quotes.

    Ie. with the example string in the above ('foo') to_yaml doesn't have to quote it, so the outputted YAML just has the foo as a bareword.

    But if you're doing something like: '-' then to_yaml will quote it with double quotes, which will stuff up your fixture because you've wrapped your erb in double quotes.

    So, upshot is, better to use single quotes around your erb: '<%= { :foo => '-' }.to_yaml %>'

Leave a Comment