Last Updated: February 25, 2016
· diasjorge

Control YAML serialization in Ruby

When serializing an object to yaml in Ruby, by default it will serialize all the instance variables of that object. This can cause some problems, Procs can't be deserialized and you may want to exclude some other variables.

This is specially useful when used with ActiveRecord to store some objects in the Database.

Fortunately Ruby offers us a hook for it.

You can specify what gets serialized to yaml like this:

def to_yaml_properties

another example:

def to_yaml_properties
  instance_variables - [:@some, :@another]

Happy serializing!