Instant Lead Alerts with Ruby and Rails

You probably already have landing pages or product detail views which you're using to generate some excellent leads for your business.  Would you like to let the sales team know when you've got a new qualified lead?

In this tutorial we'll use Twilio Programmable SMS in a Ruby on Rails application to send a message when a new lead is found.

Lead Alerts Flow

In this example we'll be implementing instant lead alerts for a fictional real estate agency.

We'll create a landing page for a house and notify a real estate agent the moment a potential customer requests information.

Learn how Porch uses Twilio SMS to send home contractors instant alerts when they are selected for a new project.

Loading Code Samples...
Language
.row
  .col-sm-8
    %h1= @house[:title]
    %h3= @house[:price]
    %p= image_tag "house.jpg", class: "img-responsive"
    %p= @house[:description]

  .col-sm-4.demo
    %h4 Talk To An Agent
    %p
      A trained real estate professional is standing by to answer any
      questions you might have about this property. Fill out the form below
      with your contact information, and an agent will reach out soon.

    = form_tag notifications_path do
      %input{type: 'hidden', name: 'house_title', value: @house[:title]}
      .form-group
        %label{for: 'name'} Your Name
        %input.form-control{name: 'name', placeholder: 'John Appleseed'}

      .form-group
        %label{for: 'phone'} Your Phone Number
        %input.form-control{name: 'phone', placeholder: '+16512229988'}

      .form-group
        %label{for: 'message'} How can we help?
        %input.form-control{name: 'message'}

      %button.btn.btn-primary{type: 'submit'} Request Info
app/views/home/index.haml
Landing page template

app/views/home/index.haml

Let's see how it works!  Click the button below to continue.

Landing Page Data

To display a landing page for our fictional house we need some data to display to web surfers.

For demonstration purposes we've created a hard-coded hash containing the information we need.

Loading Code Samples...
Language
class HomeController < ApplicationController
  def index
    @house = {
      title: '555 Sunnybrook Lane',
      price: '$349,999',
      description: 'You and your family will love this charming home. ' +
      'Featuring granite appliances, stainless steel windows, and ' +
      'high efficiency dual mud rooms, this joint is loaded to the max. ' +
      'Motivated sellers have priced for a quick sale, act now!'
    }
  end
end
app/controllers/home_controller.rb
The landing page data to expose

app/controllers/home_controller.rb

Now that our route is ready, let's see how to render the Landing Page.

Render the Landing Page

In our HAML template we insert our hard coded data about the fictional house.  We also add a form in the sidebar so the user can request more information and send in their contact info.

Loading Code Samples...
Language
.row
  .col-sm-8
    %h1= @house[:title]
    %h3= @house[:price]
    %p= image_tag "house.jpg", class: "img-responsive"
    %p= @house[:description]

  .col-sm-4.demo
    %h4 Talk To An Agent
    %p
      A trained real estate professional is standing by to answer any
      questions you might have about this property. Fill out the form below
      with your contact information, and an agent will reach out soon.

    = form_tag notifications_path do
      %input{type: 'hidden', name: 'house_title', value: @house[:title]}
      .form-group
        %label{for: 'name'} Your Name
        %input.form-control{name: 'name', placeholder: 'John Appleseed'}

      .form-group
        %label{for: 'phone'} Your Phone Number
        %input.form-control{name: 'phone', placeholder: '+16512229988'}

      .form-group
        %label{for: 'message'} How can we help?
        %input.form-control{name: 'message'}

      %button.btn.btn-primary{type: 'submit'} Request Info
app/views/home/index.haml
Landing page template

app/views/home/index.haml

Now that our landing page is ready, let's see how to set up the Twilio REST Client.

Creating a Twilio REST API Client

Now we need to create a helper class with an authenticated Twilio REST API client that we can use anytime we need to send a text message.

We initialize it with our Twilio Account Credentials stored as environment variables.  You can find the Auth Token and Account SID in the console:

console credentials

Loading Code Samples...
Language
class MessageSender
  def self.send_message(message)
    new.send_message(message)
  end

  def initialize
    # To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit
    # https://www.twilio.com/user/account
    account_sid = ENV['TWILIO_ACCOUNT_SID']
    auth_token  = ENV['TWILIO_AUTH_TOKEN']
    @client = Twilio::REST::Client.new(account_sid, auth_token)
  end

  def send_message(message)
    @client.account.messages.create(
      from:  twilio_number,
      to:    agent_number,
      body:  message
    )
  end

  private

  def twilio_number
    # A Twilio number you control - choose one from:
    # https://www.twilio.com/user/account/phone-numbers/incoming
    # Specify in E.164 format, e.g. "+16519998877"
    twilio_number = ENV['TWILIO_NUMBER']
  end

  def agent_number
    # The sales rep / agent's phone number
    agent_number = ENV['AGENT_NUMBER']
  end
end
lib/message_sender.rb
Twilio Client wrapper to facilitate sending messages

lib/message_sender.rb

Now that our Twilio Client is ready, let's have a look at how to handle an incoming lead.

Handle the Lead POST Request

This code handles the HTTP POST request issued by a user's form on our landing page. It uses our MessageSender class to send an SMS message to the real estate agent's phone number, which is stored in an environment variable.

We include the lead's name, phone number, and inquiry directly in the body of the text message sent to the agent.

Now the agent has all the information they need to follow up on the lead.

Loading Code Samples...
Language
class NotificationsController < ApplicationController
  def create
    MessageSender.send_message(message)
    redirect_to root_url,
      success: 'Thanks! An agent will be contacting you shortly.'
  rescue Twilio::REST::RequestError => error
    p error.message
    redirect_to root_url,
      error: 'Oops! There was an error. Please try again.'
  end

  private

  def message
    "New lead received for #{params[:house_title]}. " \
    "Call #{params[:name]} at #{params[:phone]}. " \
    "Message: #{params[:message]}"
  end
end
app/controllers/notifications_controller.rb
Notify sales about incoming leads

app/controllers/notifications_controller.rb

That's it! We've just implemented an application to instantly route leads to sales people using text messages.

In the next pane, we'll look at some other easy to add features for your application.

Where to next?

Ruby, Rails, and Twilio - such a great combination!  Here're a couple other great examples of integrating new features in a Ruby on Rails application:

Browser Calls

Twilio Client allows your users to make and receive phone calls in their web browsers.

Call Tracking

Call Tracking helps you measure the effectiveness of marketing campaigns.

Did this help?

Thanks for checking out this tutorial!

Tweet @twilio to let us know what you're building.

Agustin Camino
Paul Kamp
Andrew Baker
Jose Oliveros

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
.row
  .col-sm-8
    %h1= @house[:title]
    %h3= @house[:price]
    %p= image_tag "house.jpg", class: "img-responsive"
    %p= @house[:description]

  .col-sm-4.demo
    %h4 Talk To An Agent
    %p
      A trained real estate professional is standing by to answer any
      questions you might have about this property. Fill out the form below
      with your contact information, and an agent will reach out soon.

    = form_tag notifications_path do
      %input{type: 'hidden', name: 'house_title', value: @house[:title]}
      .form-group
        %label{for: 'name'} Your Name
        %input.form-control{name: 'name', placeholder: 'John Appleseed'}

      .form-group
        %label{for: 'phone'} Your Phone Number
        %input.form-control{name: 'phone', placeholder: '+16512229988'}

      .form-group
        %label{for: 'message'} How can we help?
        %input.form-control{name: 'message'}

      %button.btn.btn-primary{type: 'submit'} Request Info
class HomeController < ApplicationController
  def index
    @house = {
      title: '555 Sunnybrook Lane',
      price: '$349,999',
      description: 'You and your family will love this charming home. ' +
      'Featuring granite appliances, stainless steel windows, and ' +
      'high efficiency dual mud rooms, this joint is loaded to the max. ' +
      'Motivated sellers have priced for a quick sale, act now!'
    }
  end
end
.row
  .col-sm-8
    %h1= @house[:title]
    %h3= @house[:price]
    %p= image_tag "house.jpg", class: "img-responsive"
    %p= @house[:description]

  .col-sm-4.demo
    %h4 Talk To An Agent
    %p
      A trained real estate professional is standing by to answer any
      questions you might have about this property. Fill out the form below
      with your contact information, and an agent will reach out soon.

    = form_tag notifications_path do
      %input{type: 'hidden', name: 'house_title', value: @house[:title]}
      .form-group
        %label{for: 'name'} Your Name
        %input.form-control{name: 'name', placeholder: 'John Appleseed'}

      .form-group
        %label{for: 'phone'} Your Phone Number
        %input.form-control{name: 'phone', placeholder: '+16512229988'}

      .form-group
        %label{for: 'message'} How can we help?
        %input.form-control{name: 'message'}

      %button.btn.btn-primary{type: 'submit'} Request Info
class MessageSender
  def self.send_message(message)
    new.send_message(message)
  end

  def initialize
    # To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit
    # https://www.twilio.com/user/account
    account_sid = ENV['TWILIO_ACCOUNT_SID']
    auth_token  = ENV['TWILIO_AUTH_TOKEN']
    @client = Twilio::REST::Client.new(account_sid, auth_token)
  end

  def send_message(message)
    @client.account.messages.create(
      from:  twilio_number,
      to:    agent_number,
      body:  message
    )
  end

  private

  def twilio_number
    # A Twilio number you control - choose one from:
    # https://www.twilio.com/user/account/phone-numbers/incoming
    # Specify in E.164 format, e.g. "+16519998877"
    twilio_number = ENV['TWILIO_NUMBER']
  end

  def agent_number
    # The sales rep / agent's phone number
    agent_number = ENV['AGENT_NUMBER']
  end
end
class NotificationsController < ApplicationController
  def create
    MessageSender.send_message(message)
    redirect_to root_url,
      success: 'Thanks! An agent will be contacting you shortly.'
  rescue Twilio::REST::RequestError => error
    p error.message
    redirect_to root_url,
      error: 'Oops! There was an error. Please try again.'
  end

  private

  def message
    "New lead received for #{params[:house_title]}. " \
    "Call #{params[:name]} at #{params[:phone]}. " \
    "Message: #{params[:message]}"
  end
end