class Twilivery::DeliveryMethod

Attributes

headers[RW]
message[RW]
response[RW]
settings[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/twilivery/delivery_method.rb, line 8
def initialize(options = {})
  @settings = options
end

Public Instance Methods

deliver!(mail) click to toggle source
# File lib/twilivery/delivery_method.rb, line 12
def deliver!(mail)
  @message = prepare_message_from mail

  if @message[:to].empty?
    raise Twilivery::DeliveryException, {}
  else
    post_sms_message @message
  end
end

Private Instance Methods

cleanse_encoding(content) click to toggle source
# File lib/twilivery/delivery_method.rb, line 67
def cleanse_encoding content
  ::JSON.parse({c: content}.to_json)["c"]
end
convert_to_e164(raw_phone) click to toggle source
# File lib/twilivery/delivery_method.rb, line 71
def convert_to_e164 raw_phone
  puts "Raw: #{raw_phone}"
  PhonyRails.normalize_number(
    raw_phone.gsub(/\D/, ''),
    country_code: Twilivery.configuration.default_country_code || 'US')
end
post_sms_message(message) click to toggle source
# File lib/twilivery/delivery_method.rb, line 29
def post_sms_message message
  message[:to].each do |recipient|
    twilio.messages.create(
      from: message[:from],
      to: recipient,
      body: message[:body]
    )
  end
end
prepare_message_from(mail) click to toggle source
# File lib/twilivery/delivery_method.rb, line 39
def prepare_message_from mail
  message = {}

  # Sender
  message[:from] = mail.from.first || Twilivery.configuration.default_sms_sender

  # Recipients
  message[:to] = prepare_recipients(mail.to)
  message[:to] += prepare_recipients(mail.cc).flatten unless mail.cc.nil?
  message[:to] += prepare_recipients(mail.bcc).flatten unless mail.bcc.nil?

  # Body
  if mail.multipart?
    if mail.text_part
      message[:body] = cleanse_encoding(mail.text_part.body.to_s)
    end
  else
    message[:body] = cleanse_encoding(mail.body.to_s)
  end

  message
end
prepare_recipients(recipients) click to toggle source
# File lib/twilivery/delivery_method.rb, line 62
def prepare_recipients recipients
  recipients = [recipients] unless recipients.is_a?(Array)
  recipients.map { |r| convert_to_e164(r) }
end
twilio() click to toggle source
# File lib/twilivery/delivery_method.rb, line 25
def twilio
  @twilio ||= Twilio::REST::Client.new(Twilivery.configuration.account_sid, Twilivery.configuration.auth_token)
end