How does ruby serialization (Marshaling) work?
The Ruby marshalling methods store the type of the object they're encoding. The way those two hooks work is like this:
marshal_dump
has to return some data describing the state of your object. Ruby couldn't care less about the format of this data — it just has to be something that yourmarshal_load
method can use to reconstruct the object's state.marshal_load
is called on the marshalled object just after it's been recreated. It's basically the initialize method for a marshalled object. It's passed whatever objectmarshal_dump
returned and has to use that data to reconstruct its state.
Here's an example:
class Messenger attr_accessor :name, :message def marshal_dump {'name' => name, 'message' => message} end def marshal_load(data) self.name = data['name'] self.message = data['message'] endend
You can serialize raw numerical data using NArray as follows:
require 'narray'class NArray def _dump level Marshal.dump [to_s, typecode] + shape end def self._load arg NArray.to_na *Marshal.load(arg) endenddescribe NArray do let(:arr) { NArray[[2, 3, 5], [7, 11, 13]] } it 'should load and save an array' do dumped = Marshal.dump arr expect(Marshal.load(dumped)).to eq arr endend