8

I'm looking for a drop-in replacement of Ruby's Marshal capability, which hopefully has one or more of the following advantages over Marshal:

  • faster serialization/deserialization
  • more concise (or simply smaller) object-graph

Thanks!!

Joseph Weissman
  • 5,697
  • 5
  • 46
  • 75
  • 1
    Please make sure you don't monkey patch Marshal as I said in my comment on the accepted answer. The answer from @Adrian is great but only use `#to_msgpack` and `MessagePack::unpack` on their own. Otherwise you will break Marshal "real" functionality which is different. MsgPack is good for generic types like Array, Hash, String, etc. But Marshal works for anything in Ruby, absolutely everything. I don't think there is a "drop in" replacement exactly. It is your responsibility to know which one to use depending on what you're gonna pack. – Mig Jul 18 '20 at 08:01

2 Answers2

3

Unfortunately that doesn't work as a drop in replacement because Marshall will automatically handle complex types. Looks like msgpack will require additional functionality to be built that (like Marshal's internals) will iterate the Ruby structures that define the object in question.

Asher
  • 1,195
  • 1
  • 11
  • 19
  • 2
    Yeah, msgpack also just converts symbols to strings. This question was mostly asking for a fast library, though. – Adrian Jun 25 '10 at 01:31
2

Msgpack is focused on all of that. To replace Marshal:

require 'msgpack'

module Marshal
  module_function
  def dump(x)
    x.to_msgpack
  end
  def load(x)
    MessagePack.unpack x
  end
  alias restore load
end

http://msgpack.sourceforge.net/

Adrian
  • 14,931
  • 9
  • 45
  • 70
  • 1
    The idea is great, msgpack is a good alternative, but I don't understand why you give an example monkey patching Marshal instead of a the 2 methods for packing and unpacking. Marshal is not solving the same problem. For example you can Marshal objects. Also Marshal makes a difference between a string and a symbol. By monkey patching, you are basically breaking Marshal. Better to use msgpack the way you would use JSON. – Mig Jul 18 '20 at 07:52