Class: Cellular::Backends::Twilio

Inherits:
Backend
  • Object
show all
Defined in:
lib/cellular/backends/twilio.rb

Overview

Twilio backend (www.twilio.com)

Constant Summary collapse

API_VERSION =
'2010-04-01'.freeze
BASE_URL =
'https://api.twilio.com/'.freeze
API_URL =
BASE_URL + API_VERSION
HTTP_HEADERS =
{
  'Accept' => 'application/json',
  'Accept-Charset' => 'utf-8',
  'User-Agent' => "cellular/#{Cellular::VERSION}" \
  " (#{RUBY_ENGINE}/#{RUBY_PLATFORM}" \
  " #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL})"
}.freeze

Class Method Summary collapse

Methods inherited from Backend

receive

Class Method Details

.deliver(options = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/cellular/backends/twilio.rb', line 20

def self.deliver(options = {})
  request_queue = {}
  recipients_batch(options).each_with_index do |recipient, index|
    options[:batch] = recipient
    request = HTTParty.post(
      sms_url,
      body: payload(options),
      basic_auth: twilio_config,
      headers: HTTP_HEADERS
    )

    request_queue[index] = {
      recipient: options[:batch],
      response: parse_response(request)
    }
  end

  # return first response for now
  request_queue[0][:response]
end

.parse_response(response) ⇒ Object



41
42
43
44
45
46
# File 'lib/cellular/backends/twilio.rb', line 41

def self.parse_response(response)
  [
    response.code,
    response.message
  ]
end

.payload(options) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/cellular/backends/twilio.rb', line 59

def self.payload(options)
  {
    From: options[:sender],
    To: options[:batch],
    Body: options[:message],
    MaxPrice: options[:price] || 0.50
  }
end

.recipients_batch(options) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/cellular/backends/twilio.rb', line 68

def self.recipients_batch(options)
  if options[:recipients].blank?
    [options[:recipient]]
  else
    options[:recipients]
  end
end

.sms_urlObject



48
49
50
# File 'lib/cellular/backends/twilio.rb', line 48

def self.sms_url
  "#{API_URL}/Accounts/#{twilio_config[:username]}/Messages"
end

.twilio_configObject



52
53
54
55
56
57
# File 'lib/cellular/backends/twilio.rb', line 52

def self.twilio_config
  {
    username: Cellular.config.username,
    password: Cellular.config.password
  }
end