Skip to content

Send code via Twilio SMS

Zilvinas Kucinskas edited this page May 16, 2018 · 5 revisions

1. Create a class to manage sms

First of all, add twilio-ruby gem to your Gemfile

gem 'twilio-ruby'

Create a model to manage the sms twilio API app/models/send_code.rb

require 'twilio-ruby'

class SendCode
  def initialize
    account_sid = 'your_account_sid'
    auth_token = 'your_auth_code'
    @client = Twilio::REST::Client.new account_sid, auth_token
    @from = 'your_twilio_phone'
  end 
   
  def send_sms(options = {})
    @client.api.account.messages.create(options.merge!(from: @from))
  end
end

2. Use the class in your model

In your user model, require the SendCode class

require File.join File.dirname(__FILE__), 'send_code'

class User < ActiveRecord::Base
  has_one_time_password
  
  def authenticate(email, password)
    if email.eql?(self.email) && password.eql?(self.password)
      send_auth_code
    end
  end

  def send_auth_code
    SendCode.new.send_sms(to: self.phone, body: "Your OTP of my awesome website is #{self.otp_code}")
  end
end

Resources

https://www.twilio.com/docs/ruby/install