How to tell Ruby not to serialize an attribute or how to overload marshal_dump properly?

混江龙づ霸主 提交于 2019-12-21 06:45:06

问题


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'

I know the culprit and what I want is to set this variable to nil before any serialization takes place.

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

Or is there is way to tell Ruby or AR not to serialize an object?


回答1:


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.

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


来源:https://stackoverflow.com/questions/2767793/how-to-tell-ruby-not-to-serialize-an-attribute-or-how-to-overload-marshal-dump-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!