1. Computing

Serialization in Ruby: Marshal

By

3 of 3

Custom Serialization

Before objects are marshaled, and after they've been loaded, Ruby will attempt to call marshal_dump and marshal_load on that object. This can be used to prevent unnecessary dumping of member variables, and to allow objects with un-marshalable objects to be marshaled. In the following example, a Log class stores the filename of a log file only. When it's unmarshaled, it will re-open this log file for appending.


#!/usr/bin/env ruby

class Logfile
 def initialize(filename)
   @filename = filename

   # This IO object can't be marshaled
   @io = File.open(filename,'w')
 end

 def marshal_dump
   log "Being marshaled"

   # Dump just the filename, leave the IO object alone
   @filename
 end

 def marshal_load(filename)
   @filename = filename
   @io = File.open(@filename, 'a');
   log "Unmarshaled"
 end

 def log(message)
   @io.puts "#{Time.now}: #{message}"
 end
end

logfile = if File.exists?('logfile')
           File.open('logfile') do|file|
             Marshal.load(file)
           end
         else
           Logfile.new('log.txt')
         end

ARGV.each do|message|
 logfile.log message
end

File.open('logfile','w') do|file|
 Marshal.dump(logfile, file)
end
Serialization Methods in Ruby
  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Serialization
  6. Custom Serialization

©2014 About.com. All rights reserved.