Custom serialization in Ruby

>>>>> “M” == Minkoo Seo writes:

M> Unfortunately, Marshal::dump does not allow me to add such instance
M> variables and raises an error if such one exists.

Use #marshal_dump, #marshal_load

moulon% cat b.rb 
#!/usr/bin/ruby 
require 'logger' 
class A 
   attr_reader :a, :logger 


   def initialize 
      @a = 12 
      @logger = Logger.new(STDOUT) 
   end 


   def bar 
      @logger.info("info") 
   end 


   def marshal_dump 
      @a 
   end 


   def marshal_load(x) 
      @a = x 
      @logger = Logger.new(STDOUT) 
   end 
end 


a = A.new 
b = Marshal.load(Marshal.dump(a)) 
p b.a, b.logger.class 

 

moulon% ./b.rb 
12 
Logger 
moulon% 

Guy Decoux

p.s. 다운된 ruby-talk 와 comp.lang.ruby간의 게이트웨이는 언제살아날까요? 제가 임시 게이트웨이를 맡아서 하겠다고 올렸는데 별 반응이 없는..

Similar Posts:

Comments 3