Build your first gRPC demo with ruby

liang boyuan
3 min readMar 21, 2020

--

I have heard about gRPC for a while but what is it? And how can I use this new fancy technology with Ruby? If you also have whose questions, then just follow the article and you will find answers!

Related source code for this article: https://github.com/BranLiang/grpc-ruby-demo

First of all, I think you already checked the official gRPC repository , and their official documentations for ruby. However, in order to follow that quick start, you should clone all their example code, which covers a lot of different language, what if I just want to use ruby and start from scratch? Here I am, we will start from zero and until the last. At the end, I will conclude my thoughts about this new fancy tools.

Let’s start with an empty folder with only Gemfile. Then bundle installall necessary packages. Among them, grpcis used in code, and grpc-toolsis used for so called protocal buffer compile.

Then, you need a proto file to define your interfaces, which means you need to decide what kind communications can be made across your services. This file should be shared between client and server, so they can understand each other.

After function definitions, ruby language adapter should be generated, so you can use those defined functions in ruby. Also, if you don’t use ruby, you can also generate other language adapter files. The command is as follow.

$ mkdir lib
$ grpc_tools_ruby_protoc --ruby_out=lib --grpc_out=lib ./helloworld.proto

You should now see two new generated files, and like the comment says, DO NOT EDIT them.

Next step, we should create a server that can respond to client. There is one trick with $LOAD_PATH . The first line there enables you to require files in lib folder. And the server is pretty simple, with only one hander.

Now, you can start your first gRPC server, with following command, be sure to call that on project root path. Not in the server folder.

$ ruby ./server/server.rb

Last, create a simple client which can call server.

$ ruby client/client.rb

You should see responses from terminal now.

The demo is finished here. But we should think back about gRPC. There is one advantage for it, we can keep the client up to date with server changes easily, every time, you add a new interface or change the interface on server, you will change the proto file. Then if you want the client to update with server, you can simply copy the proto file to the client code base and run the adapter generate command. That’ it for the client code base update.

Compared with http protocal and REST way, my opinion is gRPC way is much easier to manage the interface. However, the community is still pretty early stage for gRPC, especially for ruby, so think carefully if you really want to adopt gRPC.

Cheers!

--

--