Search code examples
rubyserializationmarshallingdumpsuperclass

Modify an object before marshaling it in Ruby


I have an object containing sensitive data that I want to marshal (using Marshal) without the sensitive data.

I'd like to be able to say:

def _dump(*args)
  # Clean-up sensitive data
  super
end

but this produces a 'no superclass method' error. Is there a way I can make my object behave the way I want in response to Marshal.dump, while using the default implementation?

I want Marshal.dump(my_obj) to work out-of-the-box without requiring the API consumer to remember to call a different method.


Solution

  • It may be that there is no superclass method for _dump. If it's defined on your object it's called. If not, the default handler is used.

    You probably want to clone your object and remove the sensitive fields, returning that as a Hash inside your _dump function, then undo that within the _load method.

    You can also read the documentation on Marshal where it describes the recommended methods.