Skip to content

Instantly share code, notes, and snippets.

@kerskine
Created May 14, 2010 14:06
Show Gist options
  • Save kerskine/401184 to your computer and use it in GitHub Desktop.
Save kerskine/401184 to your computer and use it in GitHub Desktop.
class MessagesController < ApplicationController
require 'twiliolib'
require 'rexml/document'
include REXML
# Twilio REST API version
API_VERSION = '2008-08-01'
# Twilio AccountSid and AuthToken
ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
ACCOUNT_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
def create
@message = Message.new(params[:message])
# Create a Twilio REST account object using your Twilio account ID and token
account = Twilio::RestAccount.new(ACCOUNT_SID, ACCOUNT_TOKEN)
d = { 'From' => @message.From, 'To' => @message.To, 'Body' => @message.Body }
resp = account.request("/#{API_VERSION}/Accounts/#{ACCOUNT_SID}/SMS/Messages", 'POST', d)
resp.error! unless resp.kind_of? Net::HTTPSuccess
h = Document.new resp.body
s = XPath.first(h, "//Sid")
sid = s.text
@message.SmsMessageSid = sid
respond_to do |format|
if @message.save
flash[:notice] = 'Message was successfully created.'
format.html { redirect_to(@message) }
format.xml { render :xml => @message, :status => :created, :location => @message }
else
format.html { render :action => "new" }
format.xml { render :xml => @message.errors, :status => :unprocessable_entity }
end
end
end
@kerskine
Copy link
Author

OK - this isn't very pretty. In fact, I bet there are at least 3 ways to make this more readable and maintainable. I'm using the Twilio Rest Library to format the post sending texts. The Create method is based on the standard one generated from a Rails scaffold.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment