Twilio in Rails
This week I was given an assignment by a potential employer. This assignment had a few specs including adding ajax functionality to a rails app so that it would perform as a single page app.
As a bonus, one spec asked me to get Twilio ( a software that sends text messages from your application) working within the app when a new lead was created.
Heres how that went:
Step 1: Sign up for a Twilio Trial account using this link: https://www.twilio.com/try-twilio
Step 2: Set up your account by adding a twilio phone number (the number texts will be sent from)
Step 3: Create a module for sending SMS Texts and add this line of code to your application.rb file
config.autoload_paths += %W(#{config.root}/lib)
so that your file looks something like this
require_relative 'boot'require 'rails/all'# Require the gems listed in Gemfile, including any gems# you've limited to :test, :development, or :production.Bundler.require(*Rails.groups)module Pingsuranceclass Application < Rails::Application# Initialize configuration defaults for originally generated Rails version.config.load_defaults 6.0# Settings in config/environments/* take precedence over those specified here.# Application configuration can go into files in config/initializers# -- all .rb files in that directory are automatically loaded after loading# the framework and any gems in your application.config.autoload_paths += %W(#{config.root}/lib)endend
Step 4: Add the twilio-ruby , and dotenv-rails gems to your gemfile
Step 5: (Optional but recommended) add an instance method to the model that is responsible for phone numbers that will clean and format the passed in phone numbers.
Step 6: In your texting module, add a method that will be responsible for actually sending the text message, mine looks like this
module Messenger def send_sms(number, note) account_sid = ENV['TWILIO_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new account_sid, auth_token from = '+14129601023' message = @client.messages.create( from: from, to: '+1'+number, body: note ) endend
This method sets the account_sid and account_secret to the value of environment variables (look into using dotenv-rails and a .env file to set sensitive environment variables).
It then sets an instance variable to @client to the value of a new instance of Twilio::REST::Client and passing in your credentials, saving your twilio phone number to a variable, and then create your message with @client.messages.create.
Your message will require a few pieces of information that you can use a hash to store:
Who the text is coming from, where the text is going, and the content of the text message.
I’m still getting the hang of communicating through blogs so here’s a link to a youtube walkthrough of how to do this: