Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Ruby Programming
Previous Page Home Next Page

Custom Serialization Strategy

Not all objects can be dumped: bindings, procedure objects, instances of class IO, and singleton objects cannot be saved outside of the running Ruby environment (a TypeError will be raised if you try). Even if your object doesn't contain one of these problematic objects, you may want to take control of object serialization yourself.

Marshal provides the hooks you need. In the objects that require custom serialization, simply implement two methods: an instance method called _dump, which writes the object out to a string, and a class method called _load, which reads a string that you'd previously created and converts it into a new object.

For instance, here is a sample class that defines its own serialization. For whatever reasons, Special doesn't want to save one of its internal data members, ``@volatile''.

class Special
  def initialize(valuable)
    @valuable = valuable
    @volatile = "Goodbye"

  def _dump(depth)     @valuable.to_str   end

  def Special._load(str)     result =;   end

  def to_s     "#{@valuable} and #{@volatile}"   end end

a ="Hello, World") data = Marshal.dump(a) obj = Marshal.load(data) puts obj
Hello, World and Goodbye

For more details, see the reference section on Marshal beginning on page 428.
Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire