-
Notifications
You must be signed in to change notification settings - Fork 101
Serialization
BJ Neilsen edited this page Sep 13, 2013
·
10 revisions
Every message class can deserialize bytes into an instance (with decode
), and serialize an instance into bytes (with encode
).
user = Foo::User.new(:first_name => 'Bob')
bytes = user.encode #=> binary representation of this message object
user2 = Foo::User.decode(bytes)
user2 == user #=> true
Because creating a new message instance and then encoding it immediately is such a common step, you can do that directly from the class method .encode
. The following two lines of code are equivalent.
Foo::User.encode(:first_name => 'Bob')
Foo::User.new(:first_name => 'Bob').encode
Each message instance can also return a hash or JSON representation of it's key/value pairs.
Foo::User.new(:first_name => 'Bob').to_hash # => { :first_name => 'Bob' }
Foo::User.new(:first_name => 'Bob').to_json # => "{first_name:'Bob'}"