New Bamboo Web Development

Bamboo blog. Our thoughts on web technology.

Google's OpenSocial with Ruby on Rails

by Oliver Legg

Given the fair number of web applications we have developed with some aspect of social networking involved, naturally we were pretty excited about Google's OpenSocial announcement.

Looking into the OpenSocial documentation you can see that it exposes 3 different types of resources: people, that person's friends, and their activities. This structure maps nicely onto Rail's concept of nested resources, where we could have a top-level users controller with friends and activities nested underneath it.

The OpenSocial API looks quite well thought out, and built upon RESTful ideas. However it doesn't fit completely with the Rails ideals. Firstly the URL's for accessing the resources aren't the standard Rails routes and secondly it doesn't include a format extension, which means we can't use a responds_to block out of the box.

However both of these problems are easily solved by adding a few mappings to the routes file and adding our own custom mimetype. The example below shows the routing for mapping the users controller to the OpenSocial people resource.

 1 # config/environment.rb
 2 Mime::Type.register "application/x-opensocial", :opensocial
 3 
 4 # config/routes.rb
 5 map.opensocial_person '/feeds/people/:id', :controller => 'users', \
 6                             :action => 'show', :format => 'opensocial',\
 7                             :conditions => {:method => :get}
 8 
 9 map.opensocial_person '/feeds/people/:id', :controller => 'users',\
10                             :action => 'update', :format => 'opensocial', \
11                             :conditions => {:method => :put}
12 
13 map.opensocial_person '/feeds/people/:id', :controller => 'users', \
14                              :action => 'destroy', :format => 'opensocial', \
15                              :conditions => {:method => :delete}
16 
17 # app/controllers/users_controller.rb
18 
19 respond_to do |format|
20   ...
21   format.opensocial
22 end

Now you can render show.opensocial.erb or show.opensocial.builder to create atom feeds that the OpenSocial API requires.

To avoid repeating it throughout a number of applications I wrapped it up into a little plugin that just sets the routes for those three resources, like so.

 1 # config/routes.rb
 2 map.resources :users do |user|
 3   user.resources :activities
 4   user.resources :relationships
 5 end
 6 
 7 map.opensocial_people :users do |user|
 8   user.opensocial_friends :relationships
 9   user.opensocial_activities :activities
10 end

Download Plugin