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?