Context
RailsConf 2019 took place a few weeks ago, and we were there to learn about the new stuff in this popular web framework. One of the many great announcements is a new Ruby gem that allows us to interact with the Nexmo API that provides SMS, voice, and phone notifications.
In their announcement, they said, “The Nexmo Rails gem performs another integration step for you by initializing a Nexmo client instance and making it available throughout your application.”
Today we’ll help you to get started with this new tool.
Development Process
Installation
First of all, we need to add the gem into our Gemfile.
Now, we need to run `bundle install` in our terminal to use it in our web app.
Credentials
In order for us to use the power of this gem, we need to use our API key and API secret credentials found in our Nexmo account. You can sign up for a free Nexmo account here. Once you are in the dashboard, you can copy your credentials and paste them in an `.env` file, which you must create in our root directory. Here’s an example of that file content.
If you’re only interested in sending SMS, that’s all you need. If you would also like to make calls using the gem, you need to add these to your `.env` file.
We need to ensure (1) that we have the `dotenv-rails` gem and (2) that we add the `.env` file to our `.gitignore` so that we don’t mistakenly upload our credentials to our remote repository.
Initialization
The gem provides a really easy and nice way to initialize the code we need to create a client for our app by running the following command.
With this initializer, we now have the client instantiated, so we won’t need to create a new client every time we want to interact with Nexmo. Here’s an example of when we want to send an SMS.
If you want to retrieve available numbers in the US, you can do it with this piece of code.
That’s all we need to start using the Nexmo new gem. Pretty straightforward if you ask me. Now we can integrate SMS text into our app. One famous way to do that is as part of the validation of a new account where we need to make sure the phone number is the one used by our users.