Sending SMS in Ruby on Rails Application using Twilio

This article will discuss how to send an sms in a Ruby on Rails application using Twilio.

First, create an application and add a model.

1
2
3
rails new twilio-sms
rails generate model Notification body:text
rails db:create db:migrate

gem ‘twilio-ruby’

bundle install

If you don’t have a twilio account you can sign up for a free trial and go to https://www.twilio.com/console to get your keys.

Before setting up keys, first add dotenv gem to the project.

gem ‘dotenv’ bundle install

In your application root, create a file named .env. Get the keys from your console and put the keys in the .env file like this:

1
2
3
TWILIO_ACCOUNT_SID=youraccountsid
TWILIO_AUTH_TOKEN=yourauthtoken
TWILIO_PHONE_NUMBER=yourtwiliophonenumber

And then export from the terminal.

1
2
3
export TWILIO_ACCOUNT_SID=youraccountsid
export TWILIO_AUTH_TOKEN=yourauthtoken
export TWILIO_PHONE_NUMBER=yourtwiliophonenumber

Now configure Twilio. Create a file config/initializers/twilio.rb and add the following lines:

1
2
3
4
Twilio.configure do |config|
 config.account_sid = ENV["TWILIO_ACCOUNT_SID"]
 config.auth_token = ENV["TWILIO_AUTH_TOKEN"]
end

In app/models/notification.rb, add these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# app/models/notification.rb

class Notification < ApplicationRecord
 after_create :send_message

 def send_message
   client = Twilio::REST::Client.new
   client.messages.create({
                            from: ENV['TWILIO_PHONE_NUMBER'],
                            to: '923214574159',
                            body: 'Hello there! This is a test'
                          })
 end
end

That is how to send an SMS in Ruby on Rails using Twilio. Happy texting!