class BudgetSMS

Constants

API_ENDPOINTS
API_ERRORS

Attributes

msg[RW]
to[RW]

Public Class Methods

check_credit() click to toggle source
# File lib/budgetsms.rb, line 76
def check_credit
  response = get_check_credit_response
  status, credit = response.body.split(' ')

  if status == 'OK'
    logger.debug "BudgetSMS STATUS:#{status} CREDIT:#{credit}"
    credit.to_f
  else
    rise_api_error response
  end
end
send_sms(to, msg) click to toggle source
# File lib/budgetsms.rb, line 61
def send_sms to, msg
  @to = to
  @msg = msg
  response = get_sms_response

  if response.kind_of? Net::HTTPSuccess
    parse_success_sms response
  else
    message = "BudgetSMS API request failed: #{response.code} #{response.message}"
    logger.fatal message

    raise StandardError.new(message)
  end
end

Private Class Methods

get_check_credit_response() click to toggle source
# File lib/budgetsms.rb, line 105
def get_check_credit_response
  config = load_config
  uri = URI.parse(API_ENDPOINTS["CHECK_CREDIT_URL"])
  params = {
    :username => config['BUDGETSMS_USERNAME'],
    :userid => config['BUDGETSMS_USERID'],
    :handle => config['BUDGETSMS_HANDLE']
  }

  uri.query = URI.encode_www_form(params)
  Net::HTTP.get_response(uri)
end
get_sms_response() click to toggle source
# File lib/budgetsms.rb, line 118
def get_sms_response
  config = load_config
  send_sms_url = Rails.env == 'production' ? API_ENDPOINTS["SEND_SMS_URL"] : API_ENDPOINTS["TEST_SEND_SMS_URL"]
  uri = URI.parse(send_sms_url)
  params = {
    :username => config['BUDGETSMS_USERNAME'],
    :userid => config['BUDGETSMS_USERID'],
    :handle => config['BUDGETSMS_HANDLE'],
    :from => config['BUDGETSMS_FROM'],
    :to => to,
    :price => 1,
    :credit => 1,
    :msg => msg
  }

  uri.query = URI.encode_www_form(params)
  Net::HTTP.get_response(uri)
end
load_config() click to toggle source
# File lib/budgetsms.rb, line 145
def load_config
  YAML.load(ERB.new(File.read(Rails.root.join('config/budgetsms.yml'))).result)
end
logger() click to toggle source
# File lib/budgetsms.rb, line 101
def logger
  logger = Logger.new(STDOUT)
end
parse_success_sms(response) click to toggle source
# File lib/budgetsms.rb, line 90
def parse_success_sms response
  status, smsid, cost, n, credit = response.body.split(' ')

  if status == 'OK'
    logger.debug "BudgetSMS STATUS:#{status} TO:#{to}, MSG:#{msg}, SMSID:#{smsid}"
    logger.debug "BudgetSMS COST:#{cost}, CREDIT:#{credit}"
  else
    rise_api_error response
  end
end
rise_api_error(response) click to toggle source
# File lib/budgetsms.rb, line 137
def rise_api_error response
  type, error_code = response.body.split(' ')
  message = "BudgetSMS API returned not-OK: #{API_ERRORS[error_code]}"
  logger.fatal message

  raise StandardError.new(message)
end