如何告诉Ruby不要序列化属性或如何正确重载marshal_dump? [英] How to tell Ruby not to serialize an attribute or how to overload marshal_dump properly?
问题描述
我的AR:B中有一个不可序列化的属性.
I have an attribute in my AR:B that is not serializeable.
o = Discussion.find(6)
Marshal.dump(o)
TypeError: no marshal_dump is defined for class Proc
from (irb):10:in `dump'
我知道罪魁祸首,我想要将此变量设置为nil 在进行任何序列化之前.
I know the culprit and what I want is to set this variable to nil before any serialization takes place.
我可以做到这一点,但是我仍然坚持重写marshal_dump的正确方法
I can do this but I'm stuck with the proper way to override marshal_dump
def marshal_dump
@problem = nil
# what is the right return here?
end
还是有办法告诉Ruby或AR不要序列化对象?
Or is there is way to tell Ruby or AR not to serialize an object?
推荐答案
您的专用marshal_dump
应该返回一个对象,其中包含要序列化的数据.该对象将在加载时传递回marshal_load
.
Your specialized marshal_dump
should return an object containing the data you want to serialize. That object will be passed back to marshal_load
at load time.
在这种情况下,我假设您要转储的数据对应于所有AR属性(并且仅适用于那些属性),所以我尝试:
In this case, I'm assuming the data you want to dump corresponds to all AR attributes (and only those), so I'd try:
def marshal_dump
attributes
end
def marshal_load(data)
send :attributes=, data, false # false to override even protected attributes
end
这篇关于如何告诉Ruby不要序列化属性或如何正确重载marshal_dump?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!