Last active
December 16, 2016 06:53
-
-
Save mimosa/adbba446de604fc4296373dcc36d4d24 to your computer and use it in GitHub Desktop.
MessagePack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
require 'msgpack' unless defined?(::MessagePack) | |
require 'bigdecimal' unless defined?(::BigDecimal) | |
require 'time' unless Time.respond_to?(:parse) | |
class BigDecimal | |
def to_msgpack_ext | |
[to_s].pack('A*') | |
end | |
def self.from_msgpack_ext(data) # 对 String 还挺友好的,排挤 Float | |
self.new data.unpack('A*').first | |
end | |
end | |
class Time | |
def to_msgpack_ext # to_i 不够精确 | |
[xmlschema(9)].pack('A*') # yaml 保留 9位,json 只保留 3位 | |
end | |
def self.from_msgpack_ext(data) | |
self.parse data.unpack('A*').first | |
end | |
end | |
class String | |
def as_msgpack | |
MessagePack.unpack(self) | |
end | |
end | |
MessagePack::DefaultFactory.register_type(0x00, Symbol) | |
MessagePack::DefaultFactory.register_type(0x01, Time) | |
MessagePack::DefaultFactory.register_type(0x02, BigDecimal) | |
# 如果是汉字,会变增量 | |
a = { created_at: Time.now, id: 123, price: 10.239, rate: BigDecimal('1.05'), title: 'haha你好haha'} | |
b = a.to_msgpack | |
c = b.as_msgpack | |
a.to_yaml == c.to_yaml |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment