Day 6
Connecting to Twilio
I connected Prompt with Twilio today. Twilio is a service for sending text (SMS) messages, among other things. They have a really great API and if you have a need for sending texts in your application, I highly recommend them.
For a Rails application, it’s pretty easy to set up. You just include the twilio-ruby gem. In the place of your choice, you set up your Twilio client with your account variables, and start sending messages, with very little trouble. These instructions are great. I set my Twilio integration up in a class called PhoneTexter, in app/texters/phone_texter.rb, to treat it similar to the pattern of Rails mailers.
class PhoneTexter
class << self
# so I can use new_confirmation_url
# get rid of this if you don't need to use any URL helpers
include Rails.application.routes.url_helpers
end def self.send_confirmation(phone)
token = phone.token # fancy multi-line message!
line1 = "Please confirm your account by clicking this link:"
line2 = new_confirmation_url(token: token) message = "#{line1}\n\n#{line2}" send phone.number, message
end private_class_method def self.send(number, message)
# set these up with your account information
# preferably stored in environment variables
account_sid = "xxxxxxxxxxxxxxxxxxxxx"
auth_token = "xxxxxxxxxxxxxxxxxxxxx"
from = "+xxxxxxxxxxx" # your sending phone number twilio = Twilio::REST::Client.new account_sid, auth_token begin
twilio.account.sms.messages.create(
from: from,
to: number,
body: message
)
rescue Twilio::REST::RequestError => e
logger.error e.message
end
end
end
From my Phone class, I’m calling PhoneTexter.send_confirmation in an after_create action and passing in my phone object, which has the number and token ready to go. Here are the important bits:
class Phone < ApplicationRecord
after_create :send_confirmationprivate def send_confirmation
PhoneTexter.send_confirmation self
end
end
This could possibly be improved by offloading sending the confirmation to a job queue instead of doing it immediately, but I don’t want there to be any delay and I want to keep things simple for now.
What do you think? I’d love to hear feed back or suggestions for other ways to improve this.