Class: SmsXchange

Inherits:
Object
  • Object
show all
Defined in:
lib/sms_xchange.rb

Constant Summary collapse

OK =
"01"
ERRORS =
{
  "02" => "No Such User",
  "03" => "Password is wrong",
  "04" => "Domain Name of server is wrong",
  "05" => "Message not sent. Undocumented error.",
  "06" => "Phone Number is empty.",
  "07" => "SMS parameter missing. No message to send.",
  "09" => "Insufficient SMS Credits."
}
SERVER =
"https://www.smsxchange.com"
URL =
"/scripts/sendsms.asp"
PARAMS =
"userid=%s&password=%s&phone=%s&sms=%s"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ SmsXchange

Returns a new instance of SmsXchange.



25
26
27
28
29
# File 'lib/sms_xchange.rb', line 25

def initialize(opts)
  @server = opts[:server] || SERVER
  @username = opts[:username]
  @password = opts[:password]
end

Instance Attribute Details

#password ⇒ Object (readonly)

Returns the value of attribute password.



23
24
25
# File 'lib/sms_xchange.rb', line 23

def password
  @password
end

#server ⇒ Object (readonly)

Returns the value of attribute server.



23
24
25
# File 'lib/sms_xchange.rb', line 23

def server
  @server
end

#username ⇒ Object (readonly)

Returns the value of attribute username.



23
24
25
# File 'lib/sms_xchange.rb', line 23

def username
  @username
end

Instance Method Details

#get_data(phone, message, test = false) ⇒ Object

Get the data to send to the service



34
35
36
# File 'lib/sms_xchange.rb', line 34

def get_data(phone, message, test = false)
  sprintf(PARAMS, @username, @password, CGI.escape(phone), CGI.escape(message))
end

#get_error_message(code) ⇒ Object



45
46
47
# File 'lib/sms_xchange.rb', line 45

def get_error_message(code)
  sprintf "Gateway application response code %s - %s", code, ERRORS[code] || "Unknown error code"
end

#get_url ⇒ Object

Get the url for the service



41
42
43
# File 'lib/sms_xchange.rb', line 41

def get_url
  URI.parse("#{@server}#{URL}")
end

#send(phone, message) ⇒ Object

Send an sms message



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sms_xchange.rb', line 52

def send(phone, message)
  url = get_url
  url.query = get_data(phone, message, test)
  
  https = Net::HTTP.new(url.host, url.port)
  https.use_ssl = (url.scheme == 'https')
  
  res = https.get(url.request_uri)
  
  if res.code.to_i != 200
    raise Exception.new("Server responded with HTTP " + res.code)
  end
  
  if res.body != OK
    raise Exception.new(get_error_message(res.body))
  end
end