I'd suggest monkey-patching Gosu::Image::initialize so that the image stores its original file name in @file_name and just store that string when marshalling. When loading again, you'd reload the image from the string name.
class Gosu::Image
alias_method :old_initialize, :initialize
def initialize(window, file_name)
@file_name = file_name
old_initialize(window, file_name)
end
def _dump(depth)
@file_name # The only info you need to recreate an image is the filename it was originally created from.
end
def self._load(file_name)
new($window, file_name) # Create a new copy, using the stored filename.
end
end
You'd just need to set $window to the current Window before you loaded. Not tested that code, but hopefully should make it obvious one way to do this.
By kyonides
Date 2010-08-24 18:19
Edited 2010-08-24 18:23
Interesting, if it works, there won't be a need to write separate class(es) for all the images in a game... but new or initialize is a private method...
* 'new' is a public class method (Object.new(12))
* 'initialize' is a protected instance method that is called by 'new' (in theory at least, though people often make it public by not specifying the access level).
'new' is made a private class method in order to prevent direct creation via new. This is done when defining object factories or singleton classes (well, those are the uses I am aware of).
That doesn't explain why both failed and threw those error messages I posted above... I mean, I already know I can't use them the way you did in your example.
Note that this is cute, but it won't work for images loaded with Gosu::Image.load_tiles
. There's no obvious way to get around that one with a monkey patch, either, and if you do then I can promise it will be ugly. I'd recommend implementing the marshalling code in the player object and handling the image loading yourself.
Thank you for your advices, I guess I should never expect that to be easy, neat or even viable. I was just trying to avoid any possible "code duplication" so to say.
By jlnr (dev)
Date 2010-08-25 02:22
If the result from load_tiles is always directly assigned to an instance variable, then returning an extended Array from load_tiles (one that remembers its arguments) would actually work, I think :) Just pouring some oil into the fire of a tempting hackā¦
I suppose you could do that! But then you're basically delegating loading your images back to your owning object just like I suggested. :)