August 31, 2019

building a gRPC application (part 3)

This is part three of a guided demonstration on how to build an application using gRPC. Each post represents one commit; you may follow along by reading and implementing yourself.

For this lesson, let’s use the message class we generated in the pry read-eval-print-loop.

Use a message

Before jumping into implementing services and clients, we’ll take a moment to get a feel for the generated code. Since we’re using Ruby, we can use the pry gem to play with the generated code on the command line. Add it to the Gemfile:

source ''

gem 'grpc'
gem 'grpc-tools'
gem 'pry-byebug'

install, and start:

cd src/ruby
bundle install
bundle exec pry

You can then load the generated code and interact with it:

pry(main)> require './lib/user_pb'
=> true
pry(main)> alice = username: 'alice'
=> <UserInformation: username: "alice">
pry(main)> alice.to_h
=> {:username=>"alice"}
pry(main)> alice.to_json
=> "{\"username\":\"alice\"}"
pry(main)> steve = username: 'alice'
=> <UserInformation: username: "alice">
pry(main)> alice == steve
=> true
pry(main)> steve.username = 'steve'
=> "steve"
pry(main)> alice == steve
=> false

Playing around like this, you see that the generated code has intitialiation parameters, getter and setter methods, and basic methods to compare and transmute the object to other data types, such as a Hash or JSON formatted string.

This code generation is very useful for programming purposes as it takes care of much boiler plate for you. Even more importantly, the generated code contains a function to_proto that packs the data into a binary format. It’s this binary format that will be sent over HTTP/2 between gRPC services and clients.

It’s good to use a repl like pry to gain familiarity; it’s better, however, to write minimal tests to check that the behavior conforms to expectation. Such test are certainly overkill - it’s code generated directly from a static .proto file - but in case there’s any doubt about the accuracy or usage of the bindings, the test will help reassure in a repeatable fashion.

Browse the completed code for this lesson on Gitlab:

Content by © Jared Davis 2019-2020

Powered by Hugo & Kiss.