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

Messages

Given the following compiled definition of a Foo::User:

# lib/foo/user.pb.rb
module Foo
  class States < ::Protobuf::Enum
    define :AlABAMA, 1
    #...
  end

  class User < ::Protobuf::Message; end
  class Address < ::Protobuf::Message; end

  class User
    optional ::Protobuf::Field::StringField, :first_name, 1
    optional ::Protobuf::Field::StringField, :last_name, 2
    optional ::Foo::Address, :address, 3
  end

  class Address
    optional ::Protobuf::Field::StringField, :street, 1
    optional ::Protobuf::Field::StringField, :city, 2
    optional ::Foo::States, :state, 3
    optional ::Protobuf::Field::Int32, :zip_code, 4
end

We can require the .pb.rb file and create user objects in a similar style to working with a Struct. New objects can use dot-notation to get/set fields from the proto object. You can also instantiate new protos with a hash where keys are the field names. Any keys not corresponding to defined fields are silently discarded.

Whether using a the setter method or passing in values via hash, the value is processeed by the same code that will reject bad values. Notice in the example below that we can assign fields of a Message type either with the object of that type or a hash. If a hash is given the type is simply instantiated with that hash and assigned.

require 'lib/foo/user.pb'

# dot notation reading/writing fields
user = Foo::User.new
user.first_name = "Lloyd"
user.last_name = "Christmas"
user.first_name     # => "Lloyd"
user.address = Foo::Address.new({ :street => '21 Jump Street',
                                  :city => 'Alphaville',
                                  :state => Foo::States::CALIFORNIA,
                                  :zip_code => 12345 })

# or pass in the fields as a hash to the initializer (nested hashes are perfectly acceptable)
user = Foo::User.new({ :first_name => "Lloyd",
                       :last_name => "Christmas",
                       :address => { :street => '21 Jump Street',
                                     :city => 'Alphaville',
                                     :state => Foo::States::CALIFORNIA,
                                     :zip_code => 12345 } })
user.first_name     # => Lloyd
user.last_name     # => Christmas

Enums

TBD

Clone this wiki locally