Skip to content

Instantly share code, notes, and snippets.

@JYoung217
Last active November 9, 2017 19:08
Show Gist options
  • Save JYoung217/f38e7216b42632d9a2336be06a150f8f to your computer and use it in GitHub Desktop.
Save JYoung217/f38e7216b42632d9a2336be06a150f8f to your computer and use it in GitHub Desktop.
A basic walk-through of how to integrate Twilio's API with Rails 5 using the twilio-ruby gem

Modern Made Manageable

Sending SMS messages from your Rails 5 application with Twilio

Written November 9, 2017 by Jonathan Young

Web applications have come a long ways, getting increasingly more complex with business and customer needs. In the early days of web development, many developers were required to write most of their software from scratch. From managing application routing to SQL to consuming other services on the web, (mostly) every piece was built to spec. While this provided maximum control for developers, it meant that quite a bit of time was spent writing repetitive code. Today, we have the luxury of two decades of software development experience and the explosion of companies like Twilio providing valuable 3rd-party APIs to richen our own applications.

This blog post is meant to show beginners how to get a basic Rails 5 application with SMS capabilities from Twilio up and running quickly. First, let's ensure that you have Rails installed and set up a new project:

$ gem install rails
$ rails new coffee_roasts -d postgresql -T --no-turbo-links
$ cd coffee_roasts

I took a few liberties in getting the Rails Prime Stack set up for you. We changed our default database adapter from SQLite to Postgres, turned off the test-unit framework (as most people use RSPEC), and turned off Turbo Links.

While I don't recommend this for normal development, there is a Rails generator to automagically generate an entire CRUD app with a single command that is perfect for our purposes today:

$ rails generate scaffold CoffeeRoast roast_name:string roast_description:text

From there, let's run through the typical database setup:

$ bundle install
$ bundle exec rails db:drop
$ bundle exec rails db:create
$ bundle exec rails db:migrate
$ bundle exec rails db:seed

It turns that Twilio is so popular amongst Ruby developers that they created an entire gem/library to wrap around it! This makes integrating with Twilio easier than ever before. Let's add the add the following to our Gemfile:

gem 'twilio-ruby'

Let's next run the following command to get the Twilio gem installed on Ruby:

$ bundle install

From there, let's get all of the necessary things together:

  1. Sign up for Twilio's service
  2. After you sign up, Twilio will ask you to verify your phone number. With Twilio's free trial account, this is the only number you can send texts to.
  3. Verify your number
  4. Create a project name. We'll call ours Coffee Roasts.
  5. Sign up for a free Twilio Phone Number and click "Choose this Number". This number will be the Twilio number you send texts from; keep track of this number somewhere as we'll need it later in our Rails setup.
  6. Hit the little House icon on the top left corner of your dashboard. Keep track of your Account SID and Auth Token as we'll need it later in our Rails setup.

Now that we've got our Account SID, Auth Token, and Twilio phone number, we're going to add that into our config/secrets.yml file. It will look something like this:

development:
  secret_key_base: THERE WILL ALREADY BE SOME CRAZY STRING HERE. LEAVE IT THERE.
  twilio_sid:  <%= ENV.fetch("SECRET_KEY_BASE", "YOUR-TWILIO-SID-GOES-HERE") %>
  twilio_auth_token:  <%= ENV.fetch("SECRET_KEY_BASE", "YOUR-TWILIO-AUTH-TOKEN-GOES-HERE") %>
  twilio_phone_number:  <%= ENV.fetch("SECRET_KEY_BASE", "YOUR-TWILIO-TRIAL-PHONE-NUMBER-GOES-HERE") %>

Please note that you'll need to add your country code in the twilio_phone_number. For example, if your number is "(312) 555-6677", you'll enter your phone number is "+13125556677"

Pause for a second

We have a basic CRUD app that allows users to Create, Read, Update, and Destroy Coffee Roasts. Let's say your application has started to receive some reports of spam listings being added, and your administrator -- ever vigilant -- has decided to do something about it. Every time a new coffee roast is added to to the system, they want a text message letting them know. Overkill? Mayyybe. But, your administrator is the one who pays you so you nod your head and get them what they want.

We need to configure our client by adding a Twilio initializer that will be automatically loaded with Rails. Create the file config/initializers/twilio.rb and add this code:

Twilio.configure do |config|
  config.account_sid = Rails.application.secrets.twilio_sid
  config.auth_token = Rails.application.secrets.twilio_auth_token
end

Before we start writing the code in our application, let's test the integration in a console. Use bundle exec rails console to start a console and try the following - you should get a text message on the phone number you used to set up your Twilio account!

  client = Twilio::REST::Client.new
  client.messages.create({
    from: Rails.application.secrets.twilio_phone_number,
    to: 'YOUR PERSONAL PHONE NUMBER GOES HERE',
    body: 'Hello there! This is a test'
  })

If everything worked, you should receive a text message on your phone. That's pretty impressive for so little effort. Next let's add the text messaging code to a service object in our Rails application under app/services/twilio_text_messenger.rb:

class TwilioTextMessenger
  attr_reader :message

  def initialize(message)
    @message = message
  end

  def call
    client = Twilio::REST::Client.new
    client.messages.create({
      from: Rails.application.secrets.twilio_phone_number,
      to: 'YOUR PERSONAL PHONE NUMBER GOES HERE',
      body: message
    })
  end
end

Finally, let's add that service object to our coffee_roasts_controller.rb:

# POST /coffee_roasts
def create
  @coffee_roast = CoffeeRoast.new(coffee_roast_params)

  respond_to do |format|
    if @coffee_roast.save
      message = "The coffee roast '#{@coffee_roast.roast_name}' was just added."
      TwilioTextMessenger.new(message).call
      format.html { redirect_to @coffee_roast, notice: 'Coffee roast was successfully created.' }
      format.json { render :show, status: :created, location: @coffee_roast }
    else
      format.html { render :new }
      format.json { render json: @coffee_roast.errors, status: :unprocessable_entity }
    end
  end
end

And that's it! Run the server:

$ bundle exec rails server

Visit localhost:3000/coffee_roasts, create a Coffee Roast and you should get a text message! Happy hacking!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment