Purpose
This guide helps you migrate from other MessagePack implementations to the pure Ruby MessagePack library.
References
-
Serialization - Core API
-
API reference - Complete API documentation
From msgpack-ruby (C extension)
The pure Ruby implementation aims for API compatibility with msgpack-ruby.
Module name
# msgpack-ruby
MessagePack.pack(data)
# messagepack (pure Ruby)
Messagepack.pack(data)The pure Ruby version uses Messagepack (single word) instead of MessagePack.
Compatible APIs
Most core APIs are compatible:
# These work the same in both
Messagepack.pack(data)
Messagepack.unpack(data)
Messagepack.load(data)
Messagepack.dump(data)Extension types
Extension type registration is similar:
# msgpack-ruby
factory = MessagePack::Factory.new
factory.register_type(0x01, MyClass, ...)
# messagepack (pure Ruby)
factory = Messagepack::Factory.new
factory.register_type(0x01, MyClass, ...)From JSON serialization
MessagePack is a binary alternative to JSON.
Encoding data
# JSON
require 'json'
JSON.generate({name: "Alice"})
# MessagePack
require 'messagepack'
Messagepack.pack({name: "Alice"})Type differences
# JSON only supports these types
null, true, false, number, string, array, object
# MessagePack supports additional types
nil, boolean, integer, float, string, binary, array, map,
timestamp, extension typesMigration pattern
# Before (JSON)
class Cache
def save(key, value)
File.write("cache/#{key}", JSON.generate(value))
end
def load(key)
JSON.parse(File.read("cache/#{key}"))
end
end
# After (MessagePack)
class Cache
def save(key, value)
File.write("cache/#{key}", Messagepack.pack(value), mode: 'wb')
end
def load(key)
Messagepack.unpack(File.read("cache/#{key}", encoding: Encoding::BINARY))
end
endCompatibility mode
For compatibility with older MessagePack implementations:
# Use compatibility mode to avoid bin/str8 types
binary = Messagepack.pack(data, compatibility_mode: true)This ensures: * Binary data uses str16/str32 instead of bin8/bin16/bin32 * Strings use str16/str32 instead of str8
Testing your migration
Verify serialization
# Test that data round-trips correctly
def test_serialization(data)
binary = Messagepack.pack(data)
result = Messagepack.unpack(binary)
result == data
end
# Test various types
test_serialization(nil)
test_serialization(true)
test_serialization(42)
test_serialization(3.14)
test_serialization("hello")
test_serialization([1, 2, 3])
test_serialization({a: 1, b: 2})