【发布时间】:2014-05-19 09:47:19
【问题描述】:
我创建了一个由于“在运行时执行的单元元类定义”而无法编组的对象(对代码所做内容的描述是否正确?)。
这是通过以下代码执行的:
# define class X that my use singleton class metaprogramming features
# through call of method :break_marshalling!
class X
def break_marshalling!
meta_class = class << self
self
end
meta_class.send(:define_method, :method_y) do
return
end
end
end
# prepare my instance of X now
instance_of_x = X.new
# marshalling fine here
Marshal.dump instance_of_x
# break marshalling with metprogramming features
instance_of_x.break_marshalling!
Marshal.dump instance_of_x
# fails with TypeError: singleton can't be dumped
我该怎么做才能使对象编组正确?是否可以从对象instance_of_x 的class X 中“删除”单例组件?
我真的需要一个建议,因为我们的一些对象需要通过 Marshal.dump 序列化机制进行缓存。此代码在 ruby-1.9.3 中执行,但我希望它在 ruby-2.0 或 ruby-2.1 中表现相似
【问题讨论】:
-
问得好,但你引发了我最大的烦恼之一!它被称为
singleton_class。而且我们也不需要使用define_singleton_method发送黑客攻击。 -
那么@Max 您是否遇到过任何以编程方式“重置”任何 ruby 类实例的 singleton_class 的方式?可能是
remove_singleton_class_information!之类的东西? ;)
标签: ruby singleton metaprogramming marshalling