Building a Facebook Application With Ruby

Posted on: 22 April 2012

  • Komentar Dinonaktifkan pada Building a Facebook Application With Ruby

Building a Facebook Application With RubyGambar

facebook tutorialTable of Contents

With Facebook’s Graph API and the creation of the Open Graph protocol, it is now easier then ever before to read and write data from and to the “social graph”. Here’s a few of the possibilities:

  • You could turn your webpage into a fully-featured Facebook-like page, just like if you were inside Facebook.
  • You can give your users the ability to sign in with their Facebook credentials and customize their experience with parameters taken from their Facebook profiles.
  • You could add a Like button to every object in your page such as images, songs, articles, etc., and tell your users which friends of theirs have liked your content.

In this article I’ll show you how to get started by making a very simple, but functional Facebook app and deploying it to Heroku.

Sample code for the demo Sinatra application is available on GitHub.

Facebook Application Architecture

First things first, we need to understand some of the underlying architecture of a Facebook app. It’ll save us a lot of time in the long run. I swear.

A Facebook application is actually two applications: A container application and a web application.

When we create a Facebook application in the Facebook site what we are actually creating is the container of our web app.

In this article, we’re going to focus exclusively on showing you how to build the latter kind, the Canvas app.

A Canvas app is actually made up of two different parts: A container that’s defined on, and an external web app that connects to the container, supplying the specific logic, behavior and views you define.

When we initially create a Facebook application by setting up its Canvas Page, what we are actually creating is the container of our web app. To complete the Canvas analogy, think of the external web application as if it were a painting. Facebook itself would then be the stand and the container would be the canvas.

In summary, our Facebook Canvas app will be made from:

  • The stand and the canvas, hosted on Facebook.
  • Our web application, which is not different than any other application we’ve made before, is not hosted on any Facebook server; we’re going to store it on Heroku.

As far as our customers know, it will look like a single application. To get these components to work together properly it involves a process of three phases:

  • Creation
  • Association
  • Configuration

Actually, the association is part of the configuration, but I like to think of the process this way to keep things separate.


Facebook Canvas Application

This is the easiest part, you just have to go to the Facebook Developer site and setup a new application.

Create Application

Input whatever application name you want in the Application Name field, like “My Application”, then agree the terms and click the Create Application button, after passing the Security Check you’ll be presented with the Basic Information of your brand new application.

Basic Information!

Cool, we’ve created our Canvas Application, now we’d need to associate it with an existing web app.

Web application

For the moment, we’ll assume we already have a web application we’d like to associate with Facebook and we’ll assume we are hosting it in


In case you closed the previous window you can access all your applications in the My Applications page._ Click the application we just created and click the Edit Settings button.

Now, click the Facebook Integration button in the settings page.

Facebook Integration!

I’d like you to pay attention to the Canvas section, here we’ll find all the settings we need to associate our existing web app with our Canvas Application.

  • Canvas Page – It’s an unique access point for your application, say you named your application My Facebook App, your Canvas Page might be

    By the way, sometimes you’ll have to struggle to find an available name, it’s like when you want to buy a .com domain, all the common names are often taken.

  • Canvas URL – This is the URL of our web application, in this case (the trailing slash is mandatory).

Now, when our users browses to, Facebook will show them our Canvas Application (an HTML page) which contains an IFrame (inline frame) that in turn shows These kind of applications are called IFrame Canvas Applications.

Application in Canvas

An IFrame Canvas application is actually an IFrame surrounded by the Facebook chrome. The IFrame points to our web app URL.

Let’s try it with our new application.

Without any fear, change the Canvas URL to, now open the Canvas URL in your browser. What do you see? Yes, the Heroku site, this is why it looks like your web application is inside Facebook.

Canvas Type

  • FBML (Facebook Markup Language) Canvas Applications
  • IFrame Canvas Applications

As of today, 11/10/2010, Facebook still allow us to create FBML Canvas Applications but they will be deprecated by the end of 2010. Click here to see the announcement.


Now it’s time edit all the other settings to customize your application: description, logo, icon, etc. It’s a very straight-forward phase, so I won’t touch it here.

The interaction between Canvas Applications, web applications and Facebook

Facebook has two mechanisms to let our web applications interact with the data of its social graph, more precisely, with the data of the users of our application:

  • Graph API – A powerful yet simple RESTful API
  • XFBML – Enables you to incorporate FBML into your websites and IFrame Canvas Applications.

When your application wants to retrieve information from your app users you’ll use the Graph API in one way or other.

Here’s a diagram of how Facebook applications interact with the Graph API

  1. User request
  2. Facebook returns HTML code with the Facebook chrome and the IFrame
  3. The IFrame request the Canvas URL to our server
  4. Our web asks for the current user’s name to the Graph API
  5. Facebook responds in JSON format
  6. Our app builds an HTML response to show the name of the current user and it is shown in the IFrame

Graph API interaction

If our application requests the Graph API via Javascript the communication would be directly with the Facebook servers. Here’s an example:

Our application contains the following Javascript code which is by the user with a button.

  FB.api('/me', function(response) {

Facebook returns the response in JSON and its parsed by the callback function and it alerts with the name of the current user.

Call Graph API with JS

The Facebook Graph API

The Graph API enables you to read and write objects and connections in the Facebook social graph. It’s quite easy to use, and sticks very closely to RESTful architecture, which you might already be familiar with.

To understand the API, we have to think of every single thing in Facebook as objects: photos, events, comments, friends, tags, groups, etc. and we must know that every object in Facebook has an unique identifier, an ID.

Ok, let’s query the Graph API with our browser. Click the following link to see the information of the Miles Davis page.

Now you should be see the response in JSON, most likely something that looks like this:

  "id": "57796847423",
  "name": "Miles Davis",
  "picture": "",
  "link": "",
  "category": "Musicians",
  "username": "MilesDavis",
  "genre": "Jazz",
  "bio": "...",
  "fan_count": 363730

Now, we’re going to query the API passing the username as parameter:

We should get the same response.

The Graph API exposes certain public and private information of the page. By consulting the Graph API reference > Page can learn about additional access points to find different types of information (look under the Connections header).

Once of these connections is called posts, let’s try it:

Right now I see something like this:

  "data": [
      "id": "57796847423_126368887412272",
      "from": {
      "name": "Miles Davis",
      "category": "Musicians",
      "id": "57796847423"
    "message": "Drummer Lenny White on Bitches Brew",

It’s an array of Mils Davis’ Post objects, and the Graph API reference > Post page says there’s also connection called Comments and that I can access with the following URL:

Cool, we are seeing the comments of the post with ID=57796847423_126368887412272.

This is basically how the Graph API works. To learn more please go to the Graph API overview page.

So far we’ve been accessing public information, and unfortunately if we want to access private information we won’t be able to do it this way. Facebook only allows us to access private information if we have a Facebook application which is explicitly authorized by our users.


Authentications means “It’s me, and here’s my proof”

Authorization means “Now that you know who I am, would you let me do this or that?”

Facebook uses the OAuth 2.0 protocol for authentication and authorization.

The Facebook Authentication page explains the authentication process very well, but I’ll try to summarize the process with a simple graphic, let’s say we have a server running in port 3000:

Register your application to get an app ID and secret.

Redirect your users to the following URL:

If the user authorizes your application, Facebook will request the following URL:


Exchange the code for an oauth access token in the following URL

Facebook will request the callback url with the access token


Store it in a DB, cookie or wherever you want, it must be used to make requests on behalf of the user.

Authorization process

Ok, now our application has been authenticated and the user has authorized it, but you might be wondering what information we have access to.

The answer is: only the general information: email, name, etc.

This happens when we don’t specify what kind of permissions we’re asking for, so Facebook sets the default permissions.

Here is how we ask the user for extended permissions:

Once we get the access token our application will be able to access all the photos, videos and even write to the users’s wall.

That’s basically how authentication and authorization works in Facebook.

The Open Graph Protocol

So far we’ve been talking about Facebook applications, but what if we want to take advantage of all the Facebook features in our own Web pages without actually creating a Facebook application? That’s what the Open Graph Protocol was created for.

Here are some excerpts of the Open Graph Protocol documentation:

The Open Graph protocol enables you to integrate your Web pages into the social graph.

To turn your web pages into graph objects, you’ll need to add Open Graph protocol <meta> tags and the Like button to your webpages.

Here’s a list of available <meta> tags:

  • og:title – The title of your object as it should appear within the graph.
  • og:type – The type of your object.
  • og:image – An image URL which should represent your object within the graph.
  • og:url – The canonical URL of your object that will be used as its permanent ID in the graph

In addition, Facebook have extended the basic meta data to add two required fields to let us connect our pages with Facebook:

  • og:site_name – A human-readable name for your site.
  • fb:admins or fb:app_id – A comma-separated list of either Facebook user IDs or a Facebook Platform application ID that administers this page.
  • og:description – A one to two sentence description of your page.

This is a short list of tags, there are another ones you can use to define the location of a place or contact information, etc.

As you can see, this is all about the Like button and publishing stream updates when users likes our URL using the Like button, so let’s create a page and turn it into a graph object:

This would be our basic page:


    <title>Heroku Docs & FAQs</title>

    <b>Heroku Docs & FAQs</b>


And this would be our page turned into a graph object:


    <title>Heroku Docs & FAQs</title>
    <meta property="og:title" content="Heroku Docs and FAQs"/>
    <meta property="og:type" content="blog"/>
    <meta property="og:image" content=""/>
    <meta property="og:url" content=""/>
    <meta property="og:site_name" content="Heroku"/>
    <meta property="fb:admins" content="YOUR_FACEBOOK_ID_HERE"/>

    <b>Heroku Docs & FAQs</b>
    <br />
    <iframe src=";layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>


If you want to check if your meta tags are ok, you can use the og:it application, in order for this to work you can host your page in Heroku, it’s free.

Now we know all we need to start creating real Facebook applications begin learning the most important part, how to make them in Ruby (and deploy them on Heroku).

Creating a Simple Facebook App

The fun part has finally arrived, we’re about to make a simple Facebook application! How simple? It will show a simple list of links to interesting articles, a Login button, and some Like buttons.

I’ll assume you’re using Ruby 1.9.x, and that you’ve installed the Heroku Toolbelt.

If you are using any other version of Ruby I’d suggest you to install Ruby 1.9.x with RVM. If you’re going to use RVM (Ruby Version Manager) you won’t need to prefix the following commands with sudo (Unix-like OSs only).

Installing the needed gems.

We’ll need to make sure we have bundler:

$ sudo gem install bundler

If you haven’t signed up for Heroku yet, now would be a good time. Click here to see the full instructions to do so.

What other gems are we going to use?

Installing gems with Bundler

If you want to know the advantages of using Bundler please check this Yehuda Katz’ post out

Its workflow is very simple:

$ bundle init
Writing new Gemfile to ~/simplest_fb_app/Gemfile

Take into account that the gem is called Bundler while the command-line utility is called bundle

Edit the Gemfile with your preferred text editor to let it look like this:

source :gemcutter

gem 'sinatra', '1.0'
gem 'oa-oauth', '0.1.6'

Please notice we’re declaring oa-oauth as dependency, not omniauth, this is because OmniAuth is a collection of Rack middleware, in this case we’re only going to need the oauth one.

Now we need to tell Bundler to check if we’re missing the gems our application depends on, if so, tell it to install them:

$ bundle check
The following gems are missing

$ bundle install

We are all set up, let’s get started!

The first step will be to create a Canvas application in Facebook, I’ll name it Faceboku but you can name it whatever you want to.

These would be our application settings:

Site URL =

Canvas Page => (instead of faceboku you must use a different one)

Canvas URL  = http://localhost:4567 (the standard port used by Sinatra applications)

Canvas Type = IFrame

If you don’t see the Canvas Type option, don’t worry, there’s a possibility Facebook has got rid of it by the time you’re reading this.

We’re using http://localhost:4567 because that way we’ll be able to test our Facebook application before we deploy it to Heroku.

What’s next? our Sinatra application

Create a directory called simplest_fb_app wherever you want in your system, I’ll do it in my home directory:

$ mkdir ~/simplest_fb_app

then create the following files and directories on it:

  • faceboku.rb (you may use the name of your canvas application)
  • views/ (folder)
  • views/layout.erb
  • views/index.erb

I’ll let these files look like:


require 'sinatra'
require 'omniauth/oauth'

enable :sessions

#Here you have to put your own Application ID and Secret
APP_ID = "153304591365687"
APP_SECRET = "7a7663099ccb62f180d985ba1252a3e2"

use OmniAuth::Builder do
  provider :facebook, APP_ID, APP_SECRET, { :scope => 'email, status_update, publish_stream' }

get '/' do
    @articles = []
    @articles << {:title => 'Deploying Rack-based apps in Heroku', :url => ''}
    @articles << {:title => 'Learn Ruby in twenty minutes', :url => ''}

    erb :index

get '/auth/facebook/callback' do
  session['fb_auth'] = request.env['omniauth.auth']
  session['fb_token'] = session['fb_auth']['credentials']['token']
  session['fb_error'] = nil
  redirect '/'

get '/auth/failure' do
  session['fb_error'] = 'In order to use this site you must allow us access to your Facebook data<br />'
  redirect '/'

get '/logout' do
  redirect '/'

def clear_session
  session['fb_auth'] = nil
  session['fb_token'] = nil
  session['fb_error'] = nil
end like this:

require 'faceboku' #this is to load faceboku.rb

run Sinatra::Application


    <meta property="og:title" content="List of Articles"/>
      <meta property="og:type" content="website"/>
      <meta property="og:image" content=""/>
      <meta property="og:url" content=""/>
      <meta property="og:site_name" content="Heroku:Interesting Articles"/>
      <meta property="fb:admins" content="643897273"/>

      body { font-family: Arial; font-size: 20px ;}
      a { text-decoration: none; color: #333; }
      .logout a { color: #2554C7; font-size: 15px; }
      .article { font-size: 1.2em; }
      .like_site { font-size: 0.8em }
    <%= yield %>



<% if session['fb_auth'] %>
  <a href='logout'><img src='images/fb_logout_button.png'></a>
<% else %>
  <a href='auth/facebook'><img src='images/fb_login_button.png'></a>
<% end %>

<h3><%= 'Hello, ' + session['fb_auth']['user_info']['first_name'] + ', ' if session['fb_token'] %>Welcome to my list of interesting articles.</h3>

  <% @articles.each do |article| %>
    <td class='article'>- <a href='<%=article[:url]%>' target='_blank'><%=article[:title]%></a></td>
      <% if session['fb_auth'] %>
        <iframe src="<%=article[:url]%>&amp;layout=button_count&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>
      <% end %>
  <% end %>

<% if session['fb_auth'] %>
  <hr />
  <p><span class='like_site'>Do you like this site?</span></p>
  <p><iframe src=";layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe></p>
<% end %>

Wow, what an amazing application!, let’s run it and browse it!

$ ruby faceboku.rb

Open your browser and point it to http://localhost:4567.

Sinatra application!

This is an easy application, it let your users to login with their Facebook credentials, it let them like your links and the application itself.

This is a Facebook application, which means we can see it in action in the Facebook site, let’s try it, browse the following URL

Sinatra application inside Facebook!

And there it is, our super application right on Facebook.

Ok, but we can’t serve our application from our local machine all the time, we need a server must always be up and running, nothing simpler than Heroku, it’ll be a 4 steps process, let’s do it:

Assuming we are in our application directory we’ll need to turn it into a git one:

$ git init

Add all the files and directories to source control:

$ git add .

Commit them to your local repository:

$ git commit -m "First version of my facebook application"

Create the Heroku application:

$ heroku create THE_NAME_YOU_WANT

Now your app has been created, and assigned the URL Time to deploy to Heroku:

$ git push heroku master

Done! Our application has been deployed to Heroku, wouldn’t you like to see it right away? simple:

$ heroku open

Cool, it’s right there, but wait, our Canvas application is still pointing to our local machine, we now want it to point to Heroku, let’s change our Canvas URL:

Change Canvas URL!

Now let’s browse to our application and that’s it!

You can also download the code of this application.

In Conclusion

As you can see, building facebook applications with Ruby is simple and hosting with Heroku makes it even easier. However, if you’re building a large application you may want to consult a more robust Web framework, other then Sinatra. The most obvious choice here would be Rails 3.

Rails 3 and Facebook integration

I’ve found that most of the existing gems and Rails plugins are still using Facebook Connect and the Old REST API instead of the new Graph API and some of them don’t even work with Ruby 1.9 and/or Rails 3.

The following are proven to work with Ruby 1.9.x and Rails 3.0.0.

Useful Resources

Here are a few other resources you may find useful to get started integrating with Facebook, and hosting on Heroku.



Rails 3



Masukkan alamat surat elektronik Anda untuk mengikuti blog ini dan menerima pemberitahuan tentang tulisan baru melalui surat elektronik.

Bergabunglah dengan 25 pengikut lainnya

RSS Umpan yang Tidak Diketahui

  • Sebuah galat telah terjadi; umpan tersebut kemungkinan sedang anjlok. Coba lagi nanti.

Upcoming Events

Tak ada acara mendatang

Hours & Info

Lunch: 11am - 2pm
Dinner: M-Th 5pm - 11pm, Fri-Sat:5pm - 1am

Just another site

Dinding Kreatif

Jangan Takut Untuk Sukses


Just another site


Smile! You’re at the best site ever

Adhy Farazman Rummi

A topnotch site


This site is the cat’s pajamas

Korean FF NC (Staleyxh)

Love me, Like me, Review please :)

Mobon Halmahera

“Kalau kamu bukan anak raja dan engkau bukan anak ulama besar, maka jadilah penulis”.


Lihat segalanya lebih dekat. Jika kau temukan sesuatu (apapun itu), Kau berhak memilih untuk tetap tinggal atau pergi. :)

The Blog

The latest news on and the WordPress community.

%d blogger menyukai ini: