ActiveRecord, instance_eval, and PStore

I’m trying to add some per-object behaviors to objects descended from
ActiveRecord, by using after_initialize() and instance_eval(), like
this:

def after_initialize
self.instance_eval(File.read(‘customers/default.rb’))
end

(Ultimately the file path will be dynamic, this is just proof of
concept.)
default.rb just contains a few method definitions like this one:

def support_phone_num
“1-800-OBITEME”
end

Anyway, this works in the console, after instantiating the object with a
find() it responds to support_phone_num(). However, back in the
controller, I try to save the object in the session and Webrick gives me
a
500 error. development.log says:

TypeError (singleton can’t be dumped):
/usr/local/lib/ruby/1.8/pstore.rb:348:in dump' /usr/local/lib/ruby/1.8/pstore.rb:348:indump’
/usr/local/lib/ruby/1.8/pstore.rb:326:in transaction' /usr/local/lib/ruby/1.8/cgi/session/pstore.rb:90:inupdate’
/usr/local/lib/ruby/1.8/cgi/session/pstore.rb:97:in close' /usr/local/lib/ruby/1.8/cgi/session.rb:330:inclose’
/usr/local/lib/ruby/gems/1.8/gems/actionpack-1.11.2/lib/action_controller/base.rb:914:in
`close_session’
[etc.]

But I don’t understand where is the singleton that can’t be dumped? I’ve
examined the @session from inside breakpointer and I don’t see a
singleton
in there. I also tried passing a string to instance_eval() inside of a
File.read, but I get the same error. Does someone with a deep
understanding of PStore know why this doesn’t work?

Thanks,

  • A

Adrian Hosey wrote:

/usr/local/lib/ruby/1.8/pstore.rb:348:in `dump'

But I don’t understand where is the singleton that can’t be dumped? I’ve
examined the @session from inside breakpointer and I don’t see a singleton
in there. I also tried passing a string to instance_eval() inside of a
File.read, but I get the same error. Does someone with a deep
understanding of PStore know why this doesn’t work?

In Ruby, methods added to a specific instance are called singleton
methods - this is the meaning of ‘singleton’ in the error message
(rather than the Singleton design pattern, which is also recognised in
Ruby and is implemented by the Singleton module).

Ruby object serialization, as implemented in Marshal.dump, can’t handle
objects with singleton methods. I haven’t looked at the internals of
PStore, but it seems reasonable that it would have the same limitation.

HTH

Justin