Java features the ability to
serialize objects, letting you
store them somewhere and reconstitute them when needed. You might
use this facility, for instance, to save a tree of objects that
represent some portion of application state---a document, a CAD
drawing, a piece of music, and so on.
Ruby calls this kind of serialization
marshaling.
[Think of railroad marshaling yards
where individual cars are assembled in sequence into a complete
train, which is then dispatched somewhere.] Saving an object
and some or all of its components is done using the method
Marshal::dump
. Typically, you will dump an entire object tree
starting with some given object. Later on, you can reconstitute the
object using
Marshal::load
.
Here's a short example. We have a class
Chord
that holds a
collection of musical notes. We'd like to save away a particularly
wonderful chord so our grandchildren can load it into Ruby Version
23.5 and savor it, too. Let's start off with the classes for
Note
and
Chord
.
class Note
attr :value
def initialize(val)
@value = val
end
def to_s
@value.to_s
end
end
class Chord
def initialize(arr)
@arr = arr
end
def play
@arr.join('-')
end
end
|
Now we'll create our masterpiece, and use
Marshal::dump
to save
a serialized version of it to disk.
c = Chord.new( [ Note.new("G"), Note.new("Bb"),
Note.new("Db"), Note.new("E") ] )
File.open("posterity", "w+") do |f|
Marshal.dump(c, f)
end
|
Finally, our grandchildren read it in, and are transported by our
creation's beauty.
File.open("posterity") do |f|
|
chord = Marshal.load(f)
|
end
|
|
chord.play
|
� |
"G-Bb-Db-E"
|