Victus Spiritus

home

Reviving Sinatra on Mac OS X with a touch of Oauth

08 Mar 2011

I had time this weekend to kick around with a couple of Sinatra apps. First my rvm setup conked out so I reinstalled it from scratch, where the implode feature came in handy. After squaring away my ruby versions and a host of basic gems, my dev environment on the Mac required the do_postgres gem to happily bundle the Sinatra app I was working on*. After some doc reading this weekend I discovered how to point gem installs in the right direction for native dependencies.

PATH=$PATH:/Library/PostgresSQL/bin sudo gem install do_postgres

Whala! The gem installed without a hitch and my Sinatra app kicked to life.

The next trick was doing the Oauth dance. It's been many moons since I last looked at oauth but after browsing other functioning code, the cobwebs cleared and more importantly the oauth gem site reminded me of the handshake process.

Create a new consumer instance by passing it a configuration hash:

@consumer=OAuth::Consumer.new( "key","secret", {
    :site=>"https://agree2"
    })

Start the process by requesting a token

@request_token=@consumer.get_request_token
session[:request_token]=@request_token
redirect_to @request_token.authorize_url

When user returns create an access_token

@access_token=@request_token.get_access_token
@photos=@access_token.get('/photos.xml')

My particular syntax looks a little different, and that could explain why I had an issue early this morning with getting it working. Instead of an instance variable I store the request_token in a session (which has to be enabled in sinatra, ie enable :session), but this is working fine. In the callback I create an access_token by passing in the oauth_verifier to get_access_token

request_token = session[:request_token]
@access_token= request_token.get_access_token({:oauth_verifier => params[:oauth_verifier]})

I'll have to revisit my implementation later, as the complaint I'm getting is 1 of 2 expected arguments.

On a side note, there's a new omniauth gem out for grabs (wiki), and oauth2 looks well designed for usage on the dev side.

Notes:
* = the app is a spring cleaning list/follow management tool for twitter.

Related links: