Using Ruby on Rails with Facebook Platform
From Facebook Developers Wiki
Contents |
[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:
- Drop the "facebook." prefix
- Replace "." with "_"
- 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.
- 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):
- Internal Canvas Web App
- Internal IFRAME Web App
- External Web App
- 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)
Sites to Check
- RFacebook home page
- RFacebook project page
- livelearncode.com
- rfacebook questions & answers site includes rfacebook Q&A and Sightings series and more
- rfacebook questions & answers mailing list/forum - Official rfacebook Forum/Mailing List
[edit] Tutorials / Getting Started Guides / Articles
- 20-Minute Quick Start Guide for RFacebook - 10 Easy Steps to Create a Facebook App Using Rails
- How To: Tutorial on developing a Facebook application using Ruby on Rails (Part I) - Shows you how to develop a Facebook application using Ruby on Rails running in the Facebook canvas using Facebook Markup Language (FBML).
- Article: Using RFacebook to update Facebook profiles and feeds (via push) (out of date with latest RFacebook library)
- Sample routes.rb file for typical facebook application using named routes. Useful if you want to use RESTful resources but are having trouble with the "everything is a POST" nature of facebook.
[edit] Alternatives to RFacebook
Facebooker lead by Chad Fowler is an alternative Facebook API in Ruby. The RubyForge project blurb reads: Pure Ruby wrapper for Facebook REST APIs. All dependencies are part of the Ruby standard library. The latest documentation for the Facebooker Gem and plugin can be found at facebooker.rubyforge.org.
More info about Facebooker: Q: What's the difference between rfacebook and Facebooker?
There is also a Facebooker tutorial application at Facebooker Tutorial
