Using Ruby on Rails with Facebook Platform

From Facebook Developer Wiki

Jump to: navigation, search

Contents

[edit] Facebook API plugins for Rails

There are currently two public, open source options for integrating Rails projects with the Facebook platform: Facebooker (created by Chad Fowler and maintained by Mike Mangino), and RFacebook (originally led by Matt Pizzimenti).

While the rest of this page contains information about RFacebook, please be aware that RFacebook is no longer being maintained. There is a newer branch available that is not maintained by the original author.

[edit] Facebooker Rails Plugin

There is a Facebooker tutorial application at Facebooker Tutorial. Please use the installation instructions from here, as the project has been moved to Github from RubyForge. The mailing list is a Google Group.

There is also a book that serves as an introduction to Facebook using Facebooker. It is available from the Pragmatic Programmers. There is also a two part screencast .


The original RubyForge Facebooker page is at facebooker.rubyforge.org.

[edit] RFacebook Rails Plugin

[edit] Latest Documentation for RFacebook

The latest documentation for the Gem and plugin can be found at rfacebook.rubyforge.org.

[edit] Install the Ruby Gem

On the commandline, install the latest version (>= 0.9.8) of the gem:

 gem install rfacebook

More information on the download is available here: download details

[edit] Install the Rails Plugin

If you are using Rails, then you also want to install the plugin:

 script/plugin install http://rfacebook.rubyforge.org/svn/trunk/rfacebook/plugins/rfacebook

svn://rubyforge.org/var/svn/rfacebook/plugins/rfacebook has been deprecated

svn://rubyforge.org/var/svn/rfacebook/plugins/rfacebook_on_rails has been deprecated

[edit] Using the RFacebook on Rails Plugin

This section gives an overview of the features of the RFacebook on Rails.

[edit] Configuring facebook.yml

The first thing to do is set up the facebook.yml configuration.

$: rake facebook:setup

This puts a sample facebook.yml for you to edit with your own API key and secret.

[edit] External web apps

The Rails plugin should be all set for Canvas and IFrame applications, but if you are doing an external web app, you will want to add a method to your controller at this point:

  def finish_facebook_login
    # redirect to whatever your want your after-login landing page to be
  end

If you are doing an external app and you don't do a redirect here, the auth_token will remain in the URL. It won't kill you, but its ugly, and if the user hits "Refresh" on that page, RFacebook::FacebookWebSession will throw an exception that the token has already been used.


[edit] Using fbsession

Similar to the way that Rails gives you cookie and session objects, the RFacebook extensions give you a fbsession object. This object is a fully instantiated RFacebook::FacebookWebSession object in all of your Controllers and Views. You can check to see if the fbsession is valid by checking the ready? property. See the next section for information on ensuring that the session is valid using before_filters.

if fbsession.ready?
  # do stuff
end

For those of you not already familiar with RFacebook::FacebookWebSession, you can basically think of it as a thin layer on top of the Facebook API. It does all of the signature generation and HTTP requests. All you have to do is call any method defined in the documentation. All RFacebook API calls return a special HPricot XML document that can be accessed via dot syntax.

For example, to get the first and last names of some users for which you have some user ids, you would call facebook.users.getInfo:

useridA = 1234
useridB = 9876
response = fbsession.users_getInfo(:uids => [useridA, useridB], :fields => ["first_name", "last_name"])

As you can see, the way to call a method involves:

  1. Drop the "facebook." prefix
  2. Replace "." with "_"
  3. Use Ruby hash notation to specify the arguments for the method. RFacebook will automatically set up: api_key, session_key, call_id, sig, v, format, and callback - so you don't have to specify those particular arguments.
  4. Grab the XML response as a "Facepricot" document (it acts like an Hpricot document, but it has extensions that allow you to traverse the response more easily)

[edit] What the heck is a Facepricot?

PLEASE NOTE: Facepricot will likely be deprecated in version 1.0 of the API

Every RFacebook API call returns a Facepricot document. This is a wrapper for an Hpricot XML document. Note that ALL of the standard Hpricot methods apply (you can even grab the original Hpricot document via xml.hpricot and use the Hpricot stuff directly). However, a Facepricot document gives you some neat methods that simplify your code:

sess.friends_get.search("//uid").map{|xmlnode| xmlnode.inner_html} // get an array of all friend UIDs
sess.friends_get.at("//uid").inner_html // get the first UID of friends

can now be accomplished with the simpler Facepricot syntax:

sess.friends_get.uid_list // get an array of all friend UIDs
sess.friends_get.uid // get the first UID of friends

So, Facepricot is a new response format that is completely backwards compatible with the old Hpricot responses. All of your old code will work, but now you'll have a great new way to access the response data without knowing XPath.

[edit] For the more curious...

The way that RFacebook does these API calls is through the Ruby feature for handling undefined methods, called method_missing. The advantage of this approach is that no matter what additions Facebook makes to the API, RFacebook will support them without modification. The disadvantage is that the syntax is slightly more verbose than if you had made a custom Ruby method for each API method. I am considering adding a set of "convenience" methods that allow for some basic calls to be simpler.

[edit] Using the before_filters

The fbsession will only be valid if the user has installed your application, or if they have been logged in to your application. You can ensure that a user is logged in by using one of the two before_filters:

before_filter :require_facebook_login
before_filter :require_facebook_install # does not do anything for external web apps

[edit] Checking how the user is viewing your application

You can also check to see how the user is using your application:

if in_facebook_canvas?
  # the user is viewing your page in the canvas
end
if in_facebook_frame?
  # the user is viewing your page either in the canvas, or the iframe
end

[edit] Other useful things

  • you can develop locally by using the Facebook Tunnel (thanks to Evan Weaver's blog post)
  • debugging is easy using the Debug Panel
  • URLs are automatically made relative to apps.facebook.com when you are inside the canvas

[edit] Sample Applications

This section will have some recipes for making applications that interact with Facebook. There are 4 main ways to use the API (as far as I can tell):

  1. Internal Canvas Web App
  2. Internal IFRAME Web App
  3. External Web App
  4. External Desktop App

I was most interested in the Canvas approach myself, so that's the only sample so far...

[edit] Canvas Sample

This shows how to create a basic canvas application (using the FBML method). We'll call our application "foobar" just for fun.

[edit] Set up your developer account

Callback URL: http:// foobar.com/fbook/ NOTE: the trailing slash is necessary!

Canvas Page URL: http:// apps.facebook.com/foobar

Be sure the select the "Use FBML" radio button.

[edit] Install the RFacebook Gem and Plugin

Instructions for this are above


[edit] Modify any other controller in your Rails app

To ensure that the user visiting your site is fully authenticated, there are two before_filters that you can use:

  • require_facebook_login
  • require_facebook_install

The following example has a controller called "Sample" that requires users to be logged in.


class SampleController < ApplicationController
  
  before_filter :require_facebook_login
  
  def razzledazzle
    # fbsession is now a completely valid RFacebook::FacebookWebSession for the user
    response = fbsession.users_getInfo(:uids => [fbsession.session_user_id], :fields => ["first_name", "last_name"])
    @firstName = response.first_name
    @lastName = response.last_name
  end
  
end

Notice the new fbsession object. This is an RFacebook::FacebookWebSession that is all set and ready for you to use! Read #Using_fbsession above if you want more details on fbsession.

[edit] Make the razzledazzle View

In your Rails views for SampleController, add a "razzledazzle" rhtml file. Just have it display @firstName and @lastName for now.

<%= @firstName %> <%= @lastName %>

[edit] Visit your page inside Facebook

Go to http:// apps.facebook.com/foobar/sample/razzledazzle . This will call http:// foobar.com/fbook/sample/razzledazzle . Since you set up "require_facebook_login", Facebook will ask you to Grant Access to the application. Once you've done so, you should see your first and last name output in the Facebook Canvas!

[edit] How do I get Ruby help?

The best people to talk about Ruby with Facebook are Levy Klots or Luke Shepard. Send us a facebook message if you have problems. I'm sure there's more ruby developers out there - please list yourselves on the wiki!

People to Talk to:

  • Luke Shepard (works at Facebook)
  • Levy Klots (works at Facebook)
  • Matt Pizzimenti (author of RFacebook library and Rails plugin)
  • Chris Chan (works on Causes at Project Agape)
  • Blake Commagere (works on Causes at Project Agape)
  • Jimmy Kittiyachavalit (works on Causes at Project Agape)
  • Kristjan Petursson (works on Causes at Project Agape)
  • Keith Rarick (works on Causes at Project Agape)
  • Shashank Date (works at BetterLabs)
  • Carsten Nielsen
  • Tony Targonski (works at GigPark)
  • Michael Leung (works at Boldcode.com)
  • David Fugere (works at CodeGenome.com)
  • Gerald Bauer (editor of rfacbook questions & answers site)
  • Jason Rives (works at Atlanta Journal and Constitution)
  • Vlad Jebelev and Ed Lui (work at zolou.com)

Sites to Check

[edit] Tutorials / Getting Started Guides / Articles

reference