Back in the almost-prehistoric days of Winter ’11, when the Force.com REST API was but a developer preview, I wrote a quick cookbook recipe to show how to call the REST API from a Ruby Sinatra app. It was very basic, just running through a canned series of create, read, update and delete operations, but it showed the basics of using the oauth2 gem to redirect the user to authenticate at Salesforce, authorize the app, and manipulate records.
In preparation for a session I’ll be presenting at Cloudstock in San Francisco next month (register now!), I recently revisited the Sinatra cookbook recipe, bringing it up to date with the current oauth2 gem, using Dalli to persist Rack sessions in Memcache, and deploying it on Heroku. The result is a much better demonstration of how these technologies intersect.
While the core Ruby source file is reproduced in the cookbook recipe, the entire project, including detailed instructions, is online at GitHub. You can also hit the deployed app on Heroku – you’ll be prompted to authenticate to Salesforce, asked to confirm that the app can access your data, then see the account browser interface.
When I tweeted about the updated recipe earlier today, Doug Friedman asked a very germane question: “Can it handle getting a new token via refresh token? Also, any pro/con of using this vs databasedotcom gem?” Answering the second question first, when I originally wrote the sample, the databasedotcom gem did not exist. Even now, though, there is still room for both approaches; databasedotcom provides a more high level, Rails-oriented API, while oauth2 gives a more concise, low level interface well suited to Sinatra.
Going back to the first point – refresh is not handled right now; the code would have to catch the 401 error from using an expired token, refresh it, and retry the operation. I may get to this, but, if you know Ruby, and fancy a challenge, fork the project on GitHub and get to work!