Integrating SMS into your Rails app with Textmarks
The new service Textmarks offers free keywords on the sms shortcode 41411 which can be forwarded as requests to any url on your website. I recently integrated the Textmarks keyword PLANS and PLAN with Planypus, so that you can make plans with your friends right from your phone. In this post I present some tips on Textmarks integration using Rails routes.
The first step is to go to Textmarks and register your keyword. Then, set it to point to the url for your webapp (selecting the “Text from a webpage” option). Textmarks offers you variables \1 through \9 that represent the words typed by the user after your keyword, with \0 representing the entire string. I found it easier to pass the entire string and parse it in your application. So, your url should look something like http://mywebapp.com/sms/\0. The string typed by the user is escaped so that spaces turn into “+”.
Since you will typically want to register only one or two keywords with textmarks, it probably makes sense to use the notion of subcommands. For example, in the PLAN keyword, I can type PLAN 1 d to get the details of the first plan or PLAN 1 r y to rsvp yes to the first plan.
The naive implementation might be to have one action in your controller with a big if/case statement. However, we can take advantage of Rails routes to route the request for us. Here’s an example of the details and rsvp features implemented via routes:
map.with_options :controller => 'sms' do |m|
m.sms_plan 'sms/plan/:text', :action => 'rsvp',
:requirements => {:text => /^\d+\++r\++\w+/} #subcode r
m.sms_plan 'sms/plan/:text', :action => 'details',
:requirements => {:text => /^\d+\++d$/} #subcode d
end
This gives us a nice mapping between the code entered by the user to an action on the sms controller that will handle the query. In your controller action, all you have to do is use the render :text method to return the text back to the user. Be careful, though, as you’re limited to 125 characters or your message will get cut off. This is something Textmarks will remedy in the coming months with multi-packet messages. I am now toying with the idea of an acts_as_textmark plugin or textmark controller generator, though at this stage I’m not sure which parts of this process can be automated and which are application specific.
P.S. sorry for lack of code highlight. Wordpress doesn’t properly handle backslashes inside pre tags. And textmate crapped out trying to convert my code to html because of the backslashes also. I’ll have to figure out a fix later.










4 Comments