Skip to content

Instantly share code, notes, and snippets.

@sergeych
Last active December 5, 2015 14:30
Show Gist options
  • Save sergeych/ebdb996d2ac11b8604c4 to your computer and use it in GitHub Desktop.
Save sergeych/ebdb996d2ac11b8604c4 to your computer and use it in GitHub Desktop.
require 'twilio-ruby'
require 'thread'
# Simple interface to send long SMS over twilio and test it like
# ActionMailer. Requires gem twilio-ruby, and following constants from
# your twilio console: SMS_ACCOUNT_SID, SMS_ACCONT_TOKEN,SMS_FROM_NUMBER.
#
# Thread safe.
#
# Enjoy ;) real.sergeych@gmail.com
#
class TwilioSms
@@twilio_lock = Mutex.new
if defined?(Rails) && Rails.env.test?
@@deliveries = []
# in test more use TwilioSms.deliveries array which holds { to:, text:} objects
def self.deliveries
@@deliveries
end
# send an SMS
def self.send to:, text:, **kwargs
@@deliveries << OpenStruct.new({ to: to, text: text })
end
else
# send an SMS
def self.send to:, text:, **kwargs
# set up a client to talk to the Twilio REST API
@@twilio_lock.synchronize {
@@client ||= Twilio::REST::Client.new(SMS_ACCOUNT_SID, SMS_ACCONT_TOKEN)
account = @@client.account
account.messages.create({ :from => SMS_FROM_NUMBER, :to => to, :body => text })
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment