mjnissim
mjnissim

Reputation: 3112

What object can I serialize in ActiveRecord?

I'm using serialize :my_array, Array and serialize :my_hash, Hash quite happily to store settings and arrays in the database conveniently.

Which other objects can I use this way? I know I can use Struct and OpenStruct for instance, but how would I know if an object can be serialized this way with ActiveRecord? For instance, how do I know if I can use the class Set (which should have been called UniqArray, mind you) this way?

Upvotes: 2

Views: 1895

Answers (2)

mikdiet
mikdiet

Reputation: 10038

Serializing in AR uses Psych for dumping instances into yaml string.

Psych in turn knows how to serialize all objects inherited from Object (it's almost all objects in Ruby).

In general case, Psych takes all instance variables of object and dumps those as yaml fields.

There are also special cases for dumping several classes, such as Array, Class, Date, DateTime, Exception, FalseClass, Float, Hash, Integer, Module, NilClass, Range, Rational, Regexp, String, Struct, Symbol, Time, TrueClass, and some other rarely used.

As example, if we have class UniqArray < Set, and instance UniqArray.new([1,2,3]) - dumped string will be "--- !ruby/object:UniqArray\nhash:\n 1: true\n 2: true\n 3: true\n" (where hash is an instance variable name which implements set store)

Upvotes: 2

spickermann
spickermann

Reputation: 107142

This code determines a coder for serialization in Rails' serialize method:

 if [:load, :dump].all? { |x| class_name.respond_to?(x) }
   class_name
 else
   Coders::YAMLColumn.new(class_name)
 end

That means in short: a Object can be serialized if the Object itself has the methods load and dump. Or if YAML can load and dump the Object. Check it this way:

object == YAML.load(YAML.dump(object))  # with require 'yaml' in irb

Upvotes: 2

Related Questions