Marshalling objects that include 'Singleton'

T

Tom Counsell

Hello

Can someone help me? I'm trying to Marshal a class that includes
'Singleton' but all I get upon loading is an empty object.

e.g:
require 'singleton'
class SingleHash < Hash
include Singleton
end

o = SingleHash.instance
o[1] = 'hello world'

# Save the object to file
File.open( 'test', 'w' ) { |file| Marshal::dump( o, file ) }

# Leave
quit

# Restart ruby
# Redefine SingleHash class
o = nil
o = File.open( 'test' ) { |file| o = Marshal::load( file ) }
puts o[1] #=> nil ? Why didn't the contents get written to the file?

Apologies if it is obvious, but why didn't the contents of the class
get written to / reloaded from the file? Is there any way to make
this work?

Many thanks

Tom
 
R

Robert Klemme

Tom Counsell said:
Hello

Can someone help me? I'm trying to Marshal a class that includes
'Singleton' but all I get upon loading is an empty object.

e.g:
require 'singleton'
class SingleHash < Hash
include Singleton
end

o = SingleHash.instance
o[1] = 'hello world'

# Save the object to file
File.open( 'test', 'w' ) { |file| Marshal::dump( o, file ) }

# Leave
quit

# Restart ruby
# Redefine SingleHash class
o = nil
o = File.open( 'test' ) { |file| o = Marshal::load( file ) }
puts o[1] #=> nil ? Why didn't the contents get written to the file?

Apologies if it is obvious, but why didn't the contents of the class
get written to / reloaded from the file? Is there any way to make
this work?

Because you can have only one instance of a singleton class marshalling
and loading is disabled. You can use delegation, store the hash and
update with the hash if you like. Or you just don't make it a singleton,
which is probably more appropriate in this case.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top