Implementing the Ability to Send SMS Messages in Rails
This tutorial will explain how to integrate the ability to send SMS messages from our Rails application, including adding the implementation code to the helper module.
Guide Tasks
  • Read Tutorial

Now that we have our RSpec stubs live in the application we can start implementing the code for sending text messages. We're going to be using the twilio-ruby gem to integrate SMS sending functionality, so let's begin with adding it to the Gemfile:

# Gemfile

gem 'twilio-ruby', '~> 4.11.1'

Now run bundle to install the Twilio library. To get this working let's update our SmsTool module with the implementation recommended by the Twilio documentation:

# lib/sms_tool.rb

module SmsTool
  account_sid = ENV['TWILIO_ACCOUNT_SID']
  auth_token = ENV['TWILIO_AUTH_TOKEN']

  @client = Twilio::REST::Client.new account_sid, auth_token

  def self.send_sms(num, msg, app)
    @client.messages.create(
      from: ENV['TWILIO_PHONE_NUMBER'],
      to: "+1#{num}",
      body: "#{msg} from #{app}"
    )
  end
end

Let's break this down to ensure you understand everything that is going on here:

  1. We're calling the API credentials
  2. We're instantiating the Twilio Rest Client and passing it in the account credentials.
  3. We're sending the message and passing in the data from the request.

Before we can confirm that this is working, let's disable a built in Rails authentication mechanism that would block our API call. Open up the ApplicationController and comment out the protect_from_forgery method.

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :exception
end

We'll get back to this later on, but for right now simply know that it would block us testing our API call from the command line.

Now we can test this in the terminal using a curl call:

curl -X POST -d "notification[phone]=4322386131" -d "notification[body]=mymessage" -d "notification[source_app]=myapp" http://localhost:3000/notifications

If you've never used cURL before, it's a helpful tool for calling services via the command line. In this command we're passing in each of the required values via a POST call. So did it work? If all of your code is setup properly you'll get a message like this on your phone:

large

Very nice, this is now working properly and our microservice can send text messages! In the next section we'll start building out the rest of our microservice, including the ability to allow outside applications to query notifications.