0

Serialization in Ruby can be done via the built-in Marshal module. It provides methods for dumping an object and loading it.

I'm writing some serialization and wondering how an object can be loaded and all of its attributes restored, without actually calling the constructor?

For example, suppose I have a class

class Test
  def initialize(id)
    @id = id
  end
end

Suppose I serialized it to (assuming a very simplified scheme that likely doesn't work in general)

{
    "Test": {
        "id": 3
    }
}

When I want to load it back, I figured I'll just instantiate a new Test object and set its attributes. However, calling the new method will throw an exception because I didn't pass in an ID yet. Indeed, I haven't gotten to the point where I have read the ID, and in general, a constructor could take any arbitrary number of arguments, and I don't want to have to write custom logic for each and every class.

When you load the object via Marshal.load, it just somehow works. How does it work?

MxLDevs
  • 19,048
  • 36
  • 123
  • 194

1 Answers1

1

See this answer for an explanation of what the default Class::new does. You can mimic this behavior without adding the call to initialize. Instead, you would manually set the state of the class via something similar to instance_variable_set. Note, this is just a suggesstion of how you can implement this yourself. The actual Marshal.load is likely written in c, but it would do something similar.

Community
  • 1
  • 1
Max
  • 15,157
  • 17
  • 82
  • 127