Rails Serialization

2009-10-11

This morning I discovered a minor issue with Rails serialization. Any class such as

class Thing < ActiveRecord::Base
  serialize :value
end
uses YAML for serialization, and issues come up if you want to store a String object that happens to have some YAML in it:
>> my_string="---\n:this_should_be_a_string:\n- 1\n- 2\n- 3"
=> "---\n:this_should_be_a_string:\n- 1\n- 2\n- 3"
>> t=Thing.new(:value=>my_string)
=> #<Thing id: nil, value: {:this_should_be_a_string=>[1, 2, 3]}>
I checked the YAML spec and they certainly provide for this (as expected in any serious markup language), using escaped double-quotes. Things get really weird when I try to store a string representing the YAML escaped-double-quoted representation of the above string:
>> t=Thing.new(:value=>"---\n\"#{my_string.gsub("\n","\\n")}\"")
=> #<Thing id: nil, value: "---\n:this_should_be_a_string:\n- 1\n-
2\n- 3">
>> t.value
=> {:this_should_be_a_string=>[1, 2, 3]}
>> t
=> #<Thing id: nil, value: {:this_should_be_a_string=>[1, 2, 3]}>
I checked the rails source and couldn't find anything about YAML anywhere (though several instances of JSON and XML). So I don't know what's going on. I doubt this problem would come up much, but it still surprised me.

Comments

There's some javascript trying to load some comments, and if you're reading this, it's probably not working.