(09/25/10) Edit: A working version of this source code is uploaded here. Download it and follow the README to try it out!

While working on our church website, integrating with our church’s facebook fan page became a desired feature so our site maintenance team can just add an event on facebook and have it synced up to our website.

After learning about the facebook graph api, I was planning to write a library for ruby that sent out the queries and parsed the results to display on our site. However, I found the fb_graph gem written by Nov Matake and decided to try it out. The experience was extremely positive and Nov was very helpful and prompt in responding to my emails. Here’s how I integrated the facebook graph api into a ruby on rails app:

First things first, lets create a new rails application, and we’ll name it “fb_graph_app”.

1% rails new fb_graph_app

With Rails 3.0 it’s easy to install the required gems. We’ll go into the Gemfile specify that we need the fb_graph gem:

 1# Gemfile 
 2source 'http://rubygems.org'
 3
 4gem 'rails', '3.0.0'
 5
 6# Bundle edge Rails instead:
 7# gem 'rails', :git => 'git://github.com/rails/rails.git'
 8
 9gem 'sqlite3-ruby', :require => 'sqlite3'
10
11#--------------------------------------------------------------------------
12# Adding the following line tells rails we need the fb_graph gem installed
13#--------------------------------------------------------------------------
14gem 'fb_graph'
15
16#....truncated the remaining file...

Once that’s saved we can install the required gems with the following command:

1% bundle install

Now that fb_graph is installed we can start making facebook graph API! Lets first create a controller and get modify the home page. We will first generate a simple controller called home with one action called index:

1% rails g controller home index

With that command the controller and view for “home” will be generated. Now we can map the root of the server to this action by changing the config/route.rb file:

 1#config/routes.tb
 2FbGraphApp::Application.routes.draw do
 3
 4#...truncated commented stuff...
 5
 6# You can have the root of your site routed with "root"
 7# just remember to delete public/index.html.
 8root :to => "home#index"
 9
10# See how all your routes lay out with "rake routes"
11
12# This is a legacy wild controller route that's not recommended for RESTful applications.
13# Note: This route will make all actions in every controller accessible via GET requests.
14# match ':controller(/:action(/:id(.:format)))'
15end

Now log into your facebook account and register for a new app here. Using the app_id, API key and application secret we are going to create a config file facebook.yml.

 1#config/facebook.yml
 2development: &defaults
 3  app_id: #your app_id
 4  client_id: #your api key
 5  client_secret: #your client secret
 6  perms: offline_access,manage_pages
 7  page_id: #the facebook page id that you wish you pull events from
 8
 9test:
10  <<: *defaults
11
12production:
13  <<: *defaults

For this demo purpose we’re just going to pull the events from a facebook “Page”. Our church has the facebook page here, so i’ll grab the page_id from the link and insert in facebook.yml for the page_id. With that setup we can now go into our home controller to add in the calls to grab events. So lets add the following code in our home controller:

 1#app/controllers/home_controller.rb
 2class HomeController < ApplicationController
 3  def index
 4    #Load facebook.yml info
 5    config = YAML::load(File.open("#{RAILS_ROOT}/config/facebook.yml"));
 6
 7    #Instantiate a new application with our app_id so we can get an access token
 8    my_app = FbGraph::Application.new(config['production']['app_id']);
 9    acc_tok = my_app.get_access_token(config['production']['client_secret']);
10
11    #Instantiate a new page class using the page_id specified 
12    @page = FbGraph::Page.new(config['production']['page_id'], :access_token => acc_tok).fetch;
13
14    #Grab the events from the page 
15    events = @page.events.sort_by{|e| e.start_time};
16    
17    #Get the events that are upcoming
18    @upcoming_events = events.find_all{|e| e.start_time >= Time.now};
19
20    #Get the events that have passed
21    @past_events = events.find_all{|e| e.start_time < Time.now}.reverse;
22  end
23end

The above code first reads the facebook.yml file to obtain the facebook app information (line 5). It then uses the information to obtain an access token (line 7,8) so we can access events and more information [Thanks Nov for pointing this out, for the sake of this example you don’t need an access token because all information accessed from facebook is public. However, if you want to access information that’s not public (i.e. who rsvped for an event) then you need an access token]. Once an access token is obtained, we can use it access information from the page. We store the page information in an instance variable so we can display in the view later. We also use the connections provided by fb_graph to access the events that are posted in for that page (line 15). Once we get the events we sort it by the start time. Then we create 2 instance variables that store the upcoming events and the events that have already passed (line 18 and 21).

Once we have the event information we can display it in our view.

 1<!-- app/views/home/index.html.erb -->
 2<h1>Home#index</h1>
 3<p>Find me in app/views/home/index.html.erb</p>
 4
 5<h1><%= @page.name %></h1>
 6<storng>Upcoming Events:</strong> <br />
 7<hr />
 8  <% @upcoming_events.each do |event| %>
 9    <%= event.name %> - <%= event.start_time %> <br />
10  <% end %>
11<br />
12<br />
13<storng>Past Events:</strong> <br />
14<hr />
15  <% @past_events.each do |event| %>
16    <%= event.name %> - <%= event.start_time %> <br />
17  <% end %>

Now we can see the results by running the web server in rails using the following command:

1% rails server

By pointing your browser to localhost:3000 you should now see a simple page with your facebook page name and the events listed from your facebook page in your ruby on rails app! This is a very simple example of using fb_graph to access the facebook graph api to get data from facebook. To learn more about the facebook graph api see here. Nov Matake also has a sample facebook app and documentation of the fb_graph api with some examples here. Note that is a simplified example, and there are several optimizations that could be done. I simply wanted a quick and easy tutorial to get people started with using the fb_graph gem. Hopefully this can help you integrate facebook into your next ruby on rails app!

blog comments powered by Disqus

my pic Isaac Liu is currently a software engineer at Apple Inc. working on the iOS performance team. He received his Ph.D in Electrical Engineering and Computer Science at the University of California, Berkeley . His research focus was in real time systems, parallel architectures and programming models. His thesis can be found here
read more…

office 2 Infinite Loop, Cupertino, CA
email liu (dot) isaac (at) gmail (dot) com
cv html / pdf [ updated: 9/05/11 ]
others facebook linkedin twitter picasa github

Recent Blog Entries

Archive...

Tags