You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Rob Sharp edited this page Mar 14, 2016
·
10 revisions
Bytes and Streams
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 objectstream=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#=> trueuser3 == 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').encodeFoo::User.encode(:first_name=>'Bob')# The preferred encoding technique when# no manipulation of the object is necessary
Hash and JSON
Each message instance can also return a hash or JSON representation of its key/value pairs.