Last Updated: February 25, 2016
·
2.699K
· 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
  [:@id]
end

another example:

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

Happy serializing!