Here’s an under-documented but extremely useful feature of ActiveRecord.
If you’re familiar with the serialize macro you’ll know that by default ActiveRecord will serialize the given attribute to YAML, and there’s no apparent way around it, but there actually is a way hidden in serialize’s implementation.
If you provide a second argument to serialize with the class you want the serialized attribute to belong to then ActiveRecord will check whether the given class responds to .dump and .load and use those methods to serialize/deserialize the object instead of the default YAML encoder. For this to work both methods need to be defined, defining just one won’t do.
So you could have, for instance:
class Recipe < ActiveRecord::Base serialize :ingredients, IngredientsList end class IngredientsList < Array def self.dump(ingredients) ingredients ? ingredients.join("\n") : nil end def self.load(ingredients) ingredients ? new(ingredients.split("\n")) : nil end end
This is a very simplistic example (and probably not a very useful improvement over YAML serialization), but this method can become really useful when you want to use custom classes to define your serialized attribute’s logic, especially when those classes aren’t easily mappable to YAML.