开发者

Importing a Ruby class from a socket connection?

I have this idea for a client/server archetype where the server would hold a hash of Marshal.dump'ed class objects along with their version numbers. Then the client could query the server concerning the version number and import the newer version of the class before instantiating it:

class Stuff
  def methods
    gibberish
  end
end

$obj_hash["Stuff"] = [3.0, Marshal.dump(Stuff)]

The problem I'm running into is that Ruby doesn't seem to want to allow me to Marshal.load the data once I've downloaded it from the server because the cla开发者_JAVA技巧ss and its methods don't exist in the client. If I bypass this by creating a 'dummy' class I'm then unable to replace the dummy class with the Marshal.load'ed data. If I simply try to use the loaded data as a class it functions according to the contents of the dummy class rather than the downloaded one.

Is there another way to go about this? If not then I guess I could just gz the code and then eval it at the other end, but I'm trying to avoid using eval or sending easily decipherable code over the line.

Thanks in advance for any advice.


Look at what happens.

class Stuff
  def methods
    "foo"
  end
end

ruby-1.8.7-p352 :001 > Marshal.dump(Stuff) 
 => "\004\bc\bStuff"

Notice how it says nothing about "methods" or "foo." If the server isn't sending that code down the wire, how is the client supposed to know what Stuff#methods should do?

It won't. :)

To do what you want to do, you'll have to send down the code itself and eval it. You'll have to implement the versioning logic yourself, of course, and "really re-define" the classes (not just monkey-patch) them.

See are you allowed to redefine a class in ruby? or is this just in irb

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜