Skip to contentSkip to navigationSkip to topbar
On this page

Masked Phone Numbers with Ruby and Rails


This Ruby on Rails(link takes you to an external page) sample application is modeled after the amazing rental experience created by AirBnB(link takes you to an external page), but with more Klingons(link takes you to an external page).

Host users can offer rental properties which other guest users can reserve. The guest and the host can then anonymously communicate via a disposable Twilio phone number created just for a reservation. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

(warning)

Legal implications of managing communications between users

If you choose to manage communications between your users, including voice calls, text-based messages (e.g., SMS), and chat, you may need to comply with certain laws and regulations, including those regarding obtaining consent. Additional information regarding legal compliance considerations and best practices for using Twilio to manage and record communications between your users, such as when using Twilio Proxy, can be found here(link takes you to an external page).

Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.

Read how Lyft uses masked phone numbers to let customers securely contact drivers(link takes you to an external page)


Create a reservation

create-a-reservation page anchor

The first step in connecting a guest and host is creating a reservation. Here, we handle a form submission for a new reservation which contains the guest's name and phone number.

Reservation Creation Method

reservation-creation-method page anchor

app/controllers/reservations_controller.rb

1
class ReservationsController < ApplicationController
2
skip_before_filter :verify_authenticity_token, only: [:accept_or_reject, :connect_guest_to_host_sms, :connect_guest_to_host_voice]
3
before_action :set_twilio_params, only: [:connect_guest_to_host_sms, :connect_guest_to_host_voice]
4
before_filter :authenticate_user, only: [:index]
5
6
# GET /reservations
7
def index
8
@reservations = current_user.reservations.all
9
end
10
11
# GET /reservations/new
12
def new
13
@reservation = Reservation.new
14
end
15
16
def create
17
@vacation_property = VacationProperty.find(params[:reservation][:property_id])
18
@reservation = @vacation_property.reservations.create(reservation_params)
19
20
if @reservation.save
21
flash[:notice] = "Sending your reservation request now."
22
@reservation.host.check_for_reservations_pending
23
redirect_to @vacation_property
24
else
25
flash[:danger] = @reservation.errors
26
end
27
end
28
29
# webhook for twilio incoming message from host
30
def accept_or_reject
31
incoming = params[:From]
32
sms_input = params[:Body].downcase
33
begin
34
@host = User.find_by(phone_number: incoming)
35
@reservation = @host.pending_reservation
36
if sms_input == "accept" || sms_input == "yes"
37
@reservation.confirm!
38
else
39
@reservation.reject!
40
end
41
42
@host.check_for_reservations_pending
43
44
sms_reponse = "You have successfully #{@reservation.status} the reservation."
45
respond(sms_reponse)
46
rescue Exception => e
47
puts "ERROR: #{e.message}"
48
sms_reponse = "Sorry, it looks like you don't have any reservations to respond to."
49
respond(sms_reponse)
50
end
51
end
52
53
# webhook for twilio to anonymously connect the two parties
54
def connect_guest_to_host_sms
55
# Guest -> Host
56
if @reservation.guest.phone_number == @incoming_phone
57
@outgoing_number = @reservation.host.phone_number
58
59
# Host -> Guest
60
elsif @reservation.host.phone_number == @incoming_phone
61
@outgoing_number = @reservation.guest.phone_number
62
end
63
64
response = Twilio::TwiML::MessagingResponse.new
65
response.message(:body => @message, :to => @outgoing_number)
66
render text: response.to_s
67
end
68
69
# webhook for twilio -> TwiML for voice calls
70
def connect_guest_to_host_voice
71
# Guest -> Host
72
if @reservation.guest.phone_number == @incoming_phone
73
@outgoing_number = @reservation.host.phone_number
74
75
# Host -> Guest
76
elsif @reservation.host.phone_number == @incoming_phone
77
@outgoing_number = @reservation.guest.phone_number
78
end
79
response = Twilio::TwiML::VoiceResponse.new
80
response.play(url: "http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")
81
response.dial(number: @outgoing_number)
82
83
render text: response.to_s
84
end
85
86
87
private
88
# Send an SMS back to the Subscriber
89
def respond(message)
90
response = Twilio::TwiML::MessagingResponse.new
91
response.message(body: message)
92
93
render text: response.to_s
94
end
95
96
# Never trust parameters from the scary internet, only allow the white list through.
97
def reservation_params
98
params.require(:reservation).permit(:name, :guest_phone, :message)
99
end
100
101
# Load up Twilio parameters
102
def set_twilio_params
103
@incoming_phone = params[:From]
104
@message = params[:Body]
105
anonymous_phone_number = params[:To]
106
@reservation = Reservation.where(phone_number: anonymous_phone_number).first
107
end
108
109
end

Part of our reservation system is receiving reservation requests from potential renters. However, these reservations need to be confirmed. Let's see how we would handle this step.


Before the reservation is finalized, the host needs to confirm that the property is still available. Learn how to automate this process in our first AirTNG tutorial, Workflow Automation.

Once the reservation is confirmed, we need to create a Twilio number that the guest and host can use to communicate in the provision_phone_number method.

Confirm Reservation Method

confirm-reservation-method page anchor

app/models/reservation.rb

1
class Reservation < ActiveRecord::Base
2
validates :name, presence: true
3
validates :guest_phone, presence: true
4
5
enum status: [ :pending, :confirmed, :rejected ]
6
7
belongs_to :vacation_property
8
belongs_to :user
9
10
def notify_host(force = false)
11
# Don't send the message if we have more than one and we aren't being forced
12
if self.host.pending_reservations.length > 1 and !force
13
return
14
else
15
message = "You have a new reservation request from #{self.name} for #{self.vacation_property.description}:
16
17
'#{self.message}'
18
19
Reply [accept] or [reject]."
20
21
self.host.send_message_via_sms(message)
22
end
23
end
24
25
def host
26
@host = User.find(self.vacation_property[:user_id])
27
end
28
29
def guest
30
@guest = User.find_by(phone_number: self.guest_phone)
31
end
32
33
def confirm!
34
provision_phone_number
35
self.update!(status: 1)
36
end
37
38
def reject!
39
self.update!(status: 0)
40
end
41
42
def notify_guest
43
if self.status_changed? && (self.status == :confirmed || self.status == :rejected)
44
message = "Your recent request to stay at #{self.vacation_property.description} was #{self.status}."
45
self.guest.send_message_via_sms(message)
46
end
47
end
48
49
def send_message_to_guest(message)
50
message = "From #{self.host.name}: #{message}"
51
self.guest.send_message_via_sms(message, self.phone_number)
52
end
53
54
def send_message_to_host(message)
55
message = "From guest #{self.guest.name}: #{message}"
56
self.host.send_message_via_sms(message, self.phone_number)
57
end
58
59
private
60
61
def provision_phone_number
62
@client = Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
63
begin
64
# Lookup numbers in host area code, if none than lookup from anywhere
65
@numbers = @client.api.available_phone_numbers('US').local.list(area_code: self.host.area_code)
66
if @numbers.empty?
67
@numbers = @client.api.available_phone_numbers('US').local.list()
68
end
69
70
# Purchase the number & set the application_sid for voice and sms, will
71
# tell the number where to route calls/sms
72
@number = @numbers.first.phone_number
73
@client.api.incoming_phone_numbers.create(
74
phone_number: @number,
75
voice_application_sid: ENV['ANONYMOUS_APPLICATION_SID'],
76
sms_application_sid: ENV['ANONYMOUS_APPLICATION_SID']
77
)
78
79
# Set the reservation.phone_number
80
self.update!(phone_number: @number)
81
82
rescue Exception => e
83
puts "ERROR: #{e.message}"
84
end
85
end
86
end

Once the reservation is confirmed, we need to purchase a Twilio number that the guest and host can use to communicate.


Purchase a Twilio Number

purchase-a-twilio-number page anchor

Here we use a Twilio REST API Client(link takes you to an external page) to search for and buy a new phone number to associate with the reservation. When we buy the number, we designate a Twilio application that will handle webhook(link takes you to an external page) requests when the new number receives an incoming call or text.

We then save the new phone number on our Reservation model, so when our app receives calls or texts to this number, we'll know which reservation the call or text belongs to.

Provision Phone Number Method

provision-phone-number-method page anchor

app/models/reservation.rb

1
class Reservation < ActiveRecord::Base
2
validates :name, presence: true
3
validates :guest_phone, presence: true
4
5
enum status: [ :pending, :confirmed, :rejected ]
6
7
belongs_to :vacation_property
8
belongs_to :user
9
10
def notify_host(force = false)
11
# Don't send the message if we have more than one and we aren't being forced
12
if self.host.pending_reservations.length > 1 and !force
13
return
14
else
15
message = "You have a new reservation request from #{self.name} for #{self.vacation_property.description}:
16
17
'#{self.message}'
18
19
Reply [accept] or [reject]."
20
21
self.host.send_message_via_sms(message)
22
end
23
end
24
25
def host
26
@host = User.find(self.vacation_property[:user_id])
27
end
28
29
def guest
30
@guest = User.find_by(phone_number: self.guest_phone)
31
end
32
33
def confirm!
34
provision_phone_number
35
self.update!(status: 1)
36
end
37
38
def reject!
39
self.update!(status: 0)
40
end
41
42
def notify_guest
43
if self.status_changed? && (self.status == :confirmed || self.status == :rejected)
44
message = "Your recent request to stay at #{self.vacation_property.description} was #{self.status}."
45
self.guest.send_message_via_sms(message)
46
end
47
end
48
49
def send_message_to_guest(message)
50
message = "From #{self.host.name}: #{message}"
51
self.guest.send_message_via_sms(message, self.phone_number)
52
end
53
54
def send_message_to_host(message)
55
message = "From guest #{self.guest.name}: #{message}"
56
self.host.send_message_via_sms(message, self.phone_number)
57
end
58
59
private
60
61
def provision_phone_number
62
@client = Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
63
begin
64
# Lookup numbers in host area code, if none than lookup from anywhere
65
@numbers = @client.api.available_phone_numbers('US').local.list(area_code: self.host.area_code)
66
if @numbers.empty?
67
@numbers = @client.api.available_phone_numbers('US').local.list()
68
end
69
70
# Purchase the number & set the application_sid for voice and sms, will
71
# tell the number where to route calls/sms
72
@number = @numbers.first.phone_number
73
@client.api.incoming_phone_numbers.create(
74
phone_number: @number,
75
voice_application_sid: ENV['ANONYMOUS_APPLICATION_SID'],
76
sms_application_sid: ENV['ANONYMOUS_APPLICATION_SID']
77
)
78
79
# Set the reservation.phone_number
80
self.update!(phone_number: @number)
81
82
rescue Exception => e
83
puts "ERROR: #{e.message}"
84
end
85
end
86
end

Now that each reservation has a Twilio Phone Number, we can see how the application will look up reservations as guest or host calls come in.


Find a reservation when a guest or host calls

find-a-reservation-when-a-guest-or-host-calls page anchor

In our controller, we create a filter which gets executed every time Twilio asks our application how to handle an incoming call or text. This filter finds and stores the correct reservation (the one associated with the anonymous number) as an instance variable that will be used as we connect the guest and host via voice or SMS.

app/controllers/reservations_controller.rb

1
class ReservationsController < ApplicationController
2
skip_before_filter :verify_authenticity_token, only: [:accept_or_reject, :connect_guest_to_host_sms, :connect_guest_to_host_voice]
3
before_action :set_twilio_params, only: [:connect_guest_to_host_sms, :connect_guest_to_host_voice]
4
before_filter :authenticate_user, only: [:index]
5
6
# GET /reservations
7
def index
8
@reservations = current_user.reservations.all
9
end
10
11
# GET /reservations/new
12
def new
13
@reservation = Reservation.new
14
end
15
16
def create
17
@vacation_property = VacationProperty.find(params[:reservation][:property_id])
18
@reservation = @vacation_property.reservations.create(reservation_params)
19
20
if @reservation.save
21
flash[:notice] = "Sending your reservation request now."
22
@reservation.host.check_for_reservations_pending
23
redirect_to @vacation_property
24
else
25
flash[:danger] = @reservation.errors
26
end
27
end
28
29
# webhook for twilio incoming message from host
30
def accept_or_reject
31
incoming = params[:From]
32
sms_input = params[:Body].downcase
33
begin
34
@host = User.find_by(phone_number: incoming)
35
@reservation = @host.pending_reservation
36
if sms_input == "accept" || sms_input == "yes"
37
@reservation.confirm!
38
else
39
@reservation.reject!
40
end
41
42
@host.check_for_reservations_pending
43
44
sms_reponse = "You have successfully #{@reservation.status} the reservation."
45
respond(sms_reponse)
46
rescue Exception => e
47
puts "ERROR: #{e.message}"
48
sms_reponse = "Sorry, it looks like you don't have any reservations to respond to."
49
respond(sms_reponse)
50
end
51
end
52
53
# webhook for twilio to anonymously connect the two parties
54
def connect_guest_to_host_sms
55
# Guest -> Host
56
if @reservation.guest.phone_number == @incoming_phone
57
@outgoing_number = @reservation.host.phone_number
58
59
# Host -> Guest
60
elsif @reservation.host.phone_number == @incoming_phone
61
@outgoing_number = @reservation.guest.phone_number
62
end
63
64
response = Twilio::TwiML::MessagingResponse.new
65
response.message(:body => @message, :to => @outgoing_number)
66
render text: response.to_s
67
end
68
69
# webhook for twilio -> TwiML for voice calls
70
def connect_guest_to_host_voice
71
# Guest -> Host
72
if @reservation.guest.phone_number == @incoming_phone
73
@outgoing_number = @reservation.host.phone_number
74
75
# Host -> Guest
76
elsif @reservation.host.phone_number == @incoming_phone
77
@outgoing_number = @reservation.guest.phone_number
78
end
79
response = Twilio::TwiML::VoiceResponse.new
80
response.play(url: "http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")
81
response.dial(number: @outgoing_number)
82
83
render text: response.to_s
84
end
85
86
87
private
88
# Send an SMS back to the Subscriber
89
def respond(message)
90
response = Twilio::TwiML::MessagingResponse.new
91
response.message(body: message)
92
93
render text: response.to_s
94
end
95
96
# Never trust parameters from the scary internet, only allow the white list through.
97
def reservation_params
98
params.require(:reservation).permit(:name, :guest_phone, :message)
99
end
100
101
# Load up Twilio parameters
102
def set_twilio_params
103
@incoming_phone = params[:From]
104
@message = params[:Body]
105
anonymous_phone_number = params[:To]
106
@reservation = Reservation.where(phone_number: anonymous_phone_number).first
107
end
108
109
end

Next, let's see how to connect the guest and the host via SMS.


Connect the Guest and the Host via SMS

connect-the-guest-and-the-host-via-sms page anchor

Our Twilio application should be configured to send HTTP requests to this controller method on any incoming text message. Our app responds with TwiML to tell Twilio what to do in response to the message.

If the initial message sent to the anonymous number was made by the host, we forward it on to the guest. But if the message was sent by the guest, we forward it to the host.

app/controllers/reservations_controller.rb

1
class ReservationsController < ApplicationController
2
skip_before_filter :verify_authenticity_token, only: [:accept_or_reject, :connect_guest_to_host_sms, :connect_guest_to_host_voice]
3
before_action :set_twilio_params, only: [:connect_guest_to_host_sms, :connect_guest_to_host_voice]
4
before_filter :authenticate_user, only: [:index]
5
6
# GET /reservations
7
def index
8
@reservations = current_user.reservations.all
9
end
10
11
# GET /reservations/new
12
def new
13
@reservation = Reservation.new
14
end
15
16
def create
17
@vacation_property = VacationProperty.find(params[:reservation][:property_id])
18
@reservation = @vacation_property.reservations.create(reservation_params)
19
20
if @reservation.save
21
flash[:notice] = "Sending your reservation request now."
22
@reservation.host.check_for_reservations_pending
23
redirect_to @vacation_property
24
else
25
flash[:danger] = @reservation.errors
26
end
27
end
28
29
# webhook for twilio incoming message from host
30
def accept_or_reject
31
incoming = params[:From]
32
sms_input = params[:Body].downcase
33
begin
34
@host = User.find_by(phone_number: incoming)
35
@reservation = @host.pending_reservation
36
if sms_input == "accept" || sms_input == "yes"
37
@reservation.confirm!
38
else
39
@reservation.reject!
40
end
41
42
@host.check_for_reservations_pending
43
44
sms_reponse = "You have successfully #{@reservation.status} the reservation."
45
respond(sms_reponse)
46
rescue Exception => e
47
puts "ERROR: #{e.message}"
48
sms_reponse = "Sorry, it looks like you don't have any reservations to respond to."
49
respond(sms_reponse)
50
end
51
end
52
53
# webhook for twilio to anonymously connect the two parties
54
def connect_guest_to_host_sms
55
# Guest -> Host
56
if @reservation.guest.phone_number == @incoming_phone
57
@outgoing_number = @reservation.host.phone_number
58
59
# Host -> Guest
60
elsif @reservation.host.phone_number == @incoming_phone
61
@outgoing_number = @reservation.guest.phone_number
62
end
63
64
response = Twilio::TwiML::MessagingResponse.new
65
response.message(:body => @message, :to => @outgoing_number)
66
render text: response.to_s
67
end
68
69
# webhook for twilio -> TwiML for voice calls
70
def connect_guest_to_host_voice
71
# Guest -> Host
72
if @reservation.guest.phone_number == @incoming_phone
73
@outgoing_number = @reservation.host.phone_number
74
75
# Host -> Guest
76
elsif @reservation.host.phone_number == @incoming_phone
77
@outgoing_number = @reservation.guest.phone_number
78
end
79
response = Twilio::TwiML::VoiceResponse.new
80
response.play(url: "http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")
81
response.dial(number: @outgoing_number)
82
83
render text: response.to_s
84
end
85
86
87
private
88
# Send an SMS back to the Subscriber
89
def respond(message)
90
response = Twilio::TwiML::MessagingResponse.new
91
response.message(body: message)
92
93
render text: response.to_s
94
end
95
96
# Never trust parameters from the scary internet, only allow the white list through.
97
def reservation_params
98
params.require(:reservation).permit(:name, :guest_phone, :message)
99
end
100
101
# Load up Twilio parameters
102
def set_twilio_params
103
@incoming_phone = params[:From]
104
@message = params[:Body]
105
anonymous_phone_number = params[:To]
106
@reservation = Reservation.where(phone_number: anonymous_phone_number).first
107
end
108
109
end

Let's see how to connect the guest and the host via phone call next.


Connect the Guest and Host via Phone Call

connect-the-guest-and-host-via-phone-call page anchor

Our Twilio application will send HTTP requests to this method on any incoming voice call. Our app responds with TwiML instructions that tell Twilio to Play an introductory MP3 audio file and then Dial either the guest or host, depending on who initiated the call.

app/controllers/reservations_controller.rb

1
class ReservationsController < ApplicationController
2
skip_before_filter :verify_authenticity_token, only: [:accept_or_reject, :connect_guest_to_host_sms, :connect_guest_to_host_voice]
3
before_action :set_twilio_params, only: [:connect_guest_to_host_sms, :connect_guest_to_host_voice]
4
before_filter :authenticate_user, only: [:index]
5
6
# GET /reservations
7
def index
8
@reservations = current_user.reservations.all
9
end
10
11
# GET /reservations/new
12
def new
13
@reservation = Reservation.new
14
end
15
16
def create
17
@vacation_property = VacationProperty.find(params[:reservation][:property_id])
18
@reservation = @vacation_property.reservations.create(reservation_params)
19
20
if @reservation.save
21
flash[:notice] = "Sending your reservation request now."
22
@reservation.host.check_for_reservations_pending
23
redirect_to @vacation_property
24
else
25
flash[:danger] = @reservation.errors
26
end
27
end
28
29
# webhook for twilio incoming message from host
30
def accept_or_reject
31
incoming = params[:From]
32
sms_input = params[:Body].downcase
33
begin
34
@host = User.find_by(phone_number: incoming)
35
@reservation = @host.pending_reservation
36
if sms_input == "accept" || sms_input == "yes"
37
@reservation.confirm!
38
else
39
@reservation.reject!
40
end
41
42
@host.check_for_reservations_pending
43
44
sms_reponse = "You have successfully #{@reservation.status} the reservation."
45
respond(sms_reponse)
46
rescue Exception => e
47
puts "ERROR: #{e.message}"
48
sms_reponse = "Sorry, it looks like you don't have any reservations to respond to."
49
respond(sms_reponse)
50
end
51
end
52
53
# webhook for twilio to anonymously connect the two parties
54
def connect_guest_to_host_sms
55
# Guest -> Host
56
if @reservation.guest.phone_number == @incoming_phone
57
@outgoing_number = @reservation.host.phone_number
58
59
# Host -> Guest
60
elsif @reservation.host.phone_number == @incoming_phone
61
@outgoing_number = @reservation.guest.phone_number
62
end
63
64
response = Twilio::TwiML::MessagingResponse.new
65
response.message(:body => @message, :to => @outgoing_number)
66
render text: response.to_s
67
end
68
69
# webhook for twilio -> TwiML for voice calls
70
def connect_guest_to_host_voice
71
# Guest -> Host
72
if @reservation.guest.phone_number == @incoming_phone
73
@outgoing_number = @reservation.host.phone_number
74
75
# Host -> Guest
76
elsif @reservation.host.phone_number == @incoming_phone
77
@outgoing_number = @reservation.guest.phone_number
78
end
79
response = Twilio::TwiML::VoiceResponse.new
80
response.play(url: "http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")
81
response.dial(number: @outgoing_number)
82
83
render text: response.to_s
84
end
85
86
87
private
88
# Send an SMS back to the Subscriber
89
def respond(message)
90
response = Twilio::TwiML::MessagingResponse.new
91
response.message(body: message)
92
93
render text: response.to_s
94
end
95
96
# Never trust parameters from the scary internet, only allow the white list through.
97
def reservation_params
98
params.require(:reservation).permit(:name, :guest_phone, :message)
99
end
100
101
# Load up Twilio parameters
102
def set_twilio_params
103
@incoming_phone = params[:From]
104
@message = params[:Body]
105
anonymous_phone_number = params[:To]
106
@reservation = Reservation.where(phone_number: anonymous_phone_number).first
107
end
108
109
end

That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy with the help of the Twilio Ruby Helper Library.


If you're a Ruby developer working with Twilio, you might want to check out these other tutorials.

Part 1 of this Tutorial: Workflow Automation

Increase your rate of response by automating the workflows that are key to your business.

Appointment Reminders

Send your customers a text message when they have an upcoming appointment - this tutorial shows you how to do it from a background job.

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio(link takes you to an external page) to let us know what you think.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.