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"
end
def _dump(depth)
@valuable.to_str
end
def Special._load(str)
result = Special.new(str);
end
def to_s
"#{@valuable} and #{@volatile}"
end
end
a = Special.new("Hello, World")
data = Marshal.dump(a)
obj = Marshal.load(data)
puts obj
|
produces:
For more details, see the reference section on
Marshal
beginning on page 428.