Skip to content
BJ Neilsen edited this page Sep 13, 2013 · 10 revisions

.encode, #encode, and .decode

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

Other serializations

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'}"
Clone this wiki locally