Marshaling Objects

Let’s learn about marshaling objects.

We'll cover the following

Ruby can take an object and convert it into a stream of bytes that can be stored outside the application. This process is called marshaling. This saved object can later be read by another instance of the application or by a totally separate application, and a copy of the originally saved object can be reconstituted.

Potential issues

Two potential issues arise when we use marshaling.

  • First, some objects can’t be dumped. If the objects to be dumped include bindings, procedure or method objects, instances of the IO class, or singleton objects. If we try to dump anonymous classes or modules, a TypeError will be raised.

  • Second, when we load a marshaled object, Ruby needs to know the definition of the class of that object and of all the objects it contains.

Rails use marshaling to store session data. If we rely on Rails to dynamically load classes, it’s possible that a particular class may not have been defined at the point it reconstitutes session data. For that reason, use the model declaration in the controller to list all models that are marshaled. This preemptively loads the necessary classes to make marshaling work.

Now that we have the Ruby basics down, let’s implement what we learned with a slightly larger annotated example that pulls together a number of concepts. We’ll follow that with a walkthrough of special features that will help with Rails coding.

Get hands-on with 1400+ tech skills courses.