[ruby-talk:00380] Re: bury/unearth (Re: Store and load)

From: gotoken@... (GOTO Kentaro)
Date: 1999-06-03 12:30:52 UTC
List: ruby-talk #380
Hi, 

In message "[ruby-talk:00378] Re: Store and load"
    on 99/06/03, "Michael Neumann" <neumann@s-direktnet.de> writes:
>> And I have a question. How can the length of input be determined?
>> Do you think `$/' for the separator?
>I think on storing and loading complex objects not strings or integers.
>Every object should know how to load itself.

Gotcha! now I see what you say. Completely implementing of your plan
seems very difficult but I'm interested in that.  An easy solution is
Marshal. The following is restricted as same as Marshal:

class Object
  require "marshal"
  def bury(port)
    case port
    when IO;     Marshal.dump(self, port)
    when String; open(port, "w"){|port| Marshal.dump(self, port)}
    else raise TypeError.new("IO or filname is required")
    end
  end

  def Object.unearth(port)
    case port
    when IO
      Marshal.load(port)
    when String
      res = open(port, "r"){|port| Marshal.load(port)}
      unless res.kind_of? self
        raise "Buried object isn't #{self.to_s} (#{res.type})" 
      end
      res
    else
      raise TypeError.new("IO or filname is required")
    end
  end
end

"I am a string".bury("Mappe")
p String.unearth("Mappe")
p Array.unearth("Mappe") # error!

-- gotoken

In This Thread

Prev Next