-
Notifications
You must be signed in to change notification settings - Fork 101
Serialization
Rob Sharp edited this page Mar 14, 2016
·
10 revisions
Every message class can deserialize bytes into an instance (with decode
), and serialize an instance into bytes (with encode
). Alternate decode_from
and encode_to
methods exist for working directly with streams.
user = Foo::User.new(:first_name => 'Bob')
bytes = user.encode # => binary representation of this message object
stream = user.encode_to(stream) # => serialize bytes to the given stream object (StringIO, pipe, etc).
user2 = Foo::User.decode(bytes)
user3 = Foo::User.decode_from(stream) # => read from the stream object (StringIO, pipe, etc).
user2 == user #=> true
user3 == user #=> true
Since it's quite common to create a new message instance and then encode it immediately, you can do that directly from the class method .encode
. The following two lines of code are equivalent.
Foo::User.new(:first_name => 'Bob').encode
Foo::User.encode(:first_name => 'Bob') # The preferred encoding technique when
# no manipulation of the object is necessary
Each message instance can also return a hash or JSON representation of its 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'}"
Next: Environment Variables
Back: Messages & Enums