-
Notifications
You must be signed in to change notification settings - Fork 101
Compiling Definitions
Protocol Buffers are great because they allow you to clearly define data storage or data transfer packets. Google officially supports Java, C++, and Python for compilation and usage. Let's make it ruby aware!
Let's say you have a definitions/foo/user.proto
file that defines a User message.
- definitions
|- foo
|- user.pb.rb
// definitions/foo/user.proto
package foo;
message User {
optional string first_name = 1;
optional string last_name = 2;
}
Now let's compile that definition to ruby:
$ protoc -I ./definitions --ruby_out ./lib definitions/foo/user.proto
The previous line will take whatever is defined in user.proto
and
output ruby classes to the ./lib
directory, obeying the package
directive. Your ./lib
should now look like this:
- lib
|- foo
|- user.pb.rb
The generated file defs.pb.rb
should look something like this:
# lib/foo/user.pb.rb
module Foo
class User < ::Protobuf::Message; end
class User
optional ::Protobuf::Field::StringField, :first_name, 1
optional ::Protobuf::Field::StringField, :last_name, 2
end
end
Note: The generator will pre-define all message/enum classes empty and then re-open to apply the defined fields. This is to prevent circular field dependency issues.
The generated class is now just a plain old ruby object. You can use it however you wish. Recognize that you can also compile multiple protos at the same time, just use shell glob syntax.
$ protoc -I ./definitions --ruby_out ./lib definitions/**/*.proto
Next: Messages & Enums
Back: Installation