Heroku: The New Face of Facebook Development

Share this article

Last week, Heroku announced a new partnership with Facebook that integrates the Heroku hosting platform into Facebook app development. This is a mind-blowing bit of news, as it completely removes the burden of entry to Facebook application development. The simplicity and scale of Heroku with the reach of Facebook is sure to inspire some great apps and new ideas. Let’s take a quick walk through how to approach this task with Ruby.

So, you know that awesome Facebook app idea that you have? The one you won’t even tell your friends about for fear of them stealing it? The one that will make you insanely famous in the Facebook and social media community? Now, thanks to Heroku, you can focus on making it great and not on how you will host it.

In the old days (which, in this case, was last week) the burgeoning Facebook developer had to figure out where to host a world-changing Facebook app. This meant provisioning VMs on a cloud provider, installing all the infrastructure (web servers, proxies, and gems – oh my!) and writing the various bits of code to handle OAuth authentication and the Facebook Graph API.

Those days are gone, my friend, for today I hope to show you the new days: days filled with not thinking about infrastructure; days filled with business logic, rainbows, and unicorns (or whatever your users have “liked” on Facebook); days where Facebook app development is just a couple of mouse-clicks and terminal commands away.

Stalker

In the post linked to above, the basic Facebook app on Heroku process is well described. If you haven’t read it, go do that now (really …  go do that). Heroku was nice enough to also do a screencast that shows the app creation process for a Ruby app with a very basic app change. Once you recover from the shock and disbelief of how easy this all is, go ahead and create an app using that walk-through.

I am calling mine “Stalker” and using Ruby as the language (duh). You’ll have to download the Heroku Toolbelt for your platform and make sure heroku login is working from your terminal. Also, make sure you have a local git repository for your Heroku app (my app’s name is ‘floating-mountain-9900’) and we should be all ready for launch. Prepare for awesome.

Application Structure

There isn’t much to the application structure. We have a Gemfile to manage our dependencies with Bundler (yay!), an app.rb file for the main app logic, a config.ru file to configure Rack, and two directories: public and views. The only view file is index.erb, so let’s take a gander inside our view.

The View (better than the one on TV)

The index.erb file is just an HTML file with pieces of ERB sprinkled about. The first ERB tag we see is the title of the app in the head section:

<title><%= @app.name %></title>

If you are familiar with ERB templates, this should be both familiar and comforting. You can structure your Facebook application page using the templating tools of Ruby. Following the title are a bunch of meta tags. These tags are important if you want good exposure for your app inside Facebook and are fully explained here. I made mine look like:

<meta property="og:title" content="Stalker"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://floating-mountain-9900.Herokuapp.com/"/>
<meta property="og:image" content=""/>
<meta property="og:site_name" content="Stalker"/>
<meta property="fb:app_id" content="<%= @app.id %>" />

I didn’t make an image, but you would certainly want to do that. Also, you might want to replace your URL with a custom domain, which is a simple (and free!) add-on for your Heroku app.

Also, in the head section, you can see the screen.css file linked, which gives you an idea of how to change the styles on the page. The stylesheets are stored in the public/stylesheets directory, which should fit you Rails/Sinatra developers like a warm coat. Any images that you want to include in your application page are stored in public/images, which is also a well-known Ruby idiom.

Continuing in the view, we start to see some VERY interesting items: instance variables. If you look for the section tag with an id of samples, this page gives examples of showing some of the user’s friends (@friends), photos (@photos), and even friends using your new app (@friends_using_app). Where do these variables come from? How do you hydrate them with data? Can it really be this easy? For that, we need to open the app.rb file.

Application File

The main file of your Facebook app is the app.rb file. If you are familiar with Sinatra (and Rubysource readers should be, thanks to Darren’s awesome Sintra series) then you must be crooning like Ol’ Blue Eyes himself. it’s just a Sinatra app, and all the magic happens in the root (“/”) handler, which we’ll talk about in a minute.

Starting at the top of the file, there are a couple of requires:

require 'sinatra'
require 'mogli'

We know why Sinatra is needed, but what is mogli? Well, mogli is a gem that purports to be the “Facebook Open Graph Library for Ruby”. This means that, as a Ruby developer, you have full access to the Graph API in the app. Pretty nifty, eh? Mogli is handling the OAuth authentication to Facebook (see the /auth/facebook handler in the file for how) and providing access to the current user (in the ‘/’ or root handler)

@user = Mogli::User.find("me", @client)

as well as all the user’s objects

@friends = @user.friends[0, 4]
@photos  = @user.photos[0, 16]
@likes   = @user.likes[0, 4]

# for other data you can always run fql
@friends_using_app = @client.fql_query("SELECT uid, name, is_app_user, pic_square FROM user WHERE uid in (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1")

There are the instance variables we saw in the view. Niiice. Look at that last variable, @friends_using_app, in particular. It’s using FQL so all of the power of the Facebook API is just an FQL string away.

The last line of the root handler hydrates and creates the view using the views/index.erb template:

erb :index

Simple as E-R-B.

Accessing User Fields

Stalker is going to print the attributes of a random friend. For fun, we’ll have it print Name, Gender, Hometown, and Birthday. The first two (Name and Gender) do not require an access token, but the latter two do. We need to tell our app that. Search for FACEBOOK_SCOPE and change it to:

FACEBOOK_SCOPE = 'publish_actions,user_likes,user_photos,user_photo_video_tags,friends_hometown,friends_birthday'

We added friends_hometown,friends_birthday to the scope so our app will now prompt the user when they first open Stalker and ask if Stalker can see Hometowns and Birthdays. All of the fields you can ask for, and how to ask for them, can be found here.

This constant is used in the authentication handler:

get "/auth/facebook" do
  session[:at]=nil
  redirect authenticator.authorize_url(:scope => FACEBOOK_SCOPE, :display => 'page')
end

when the app is being authorized.

Make Stalker

Now that we know the background of the app, let’s quickly create Stalker. Basically, Stalker is going to allow the user to type in a friend’s name, and then show some of the attributes and a picture of that friend. It’s a bit stalky, but in a non-creepy way (I hope). I followed the Working Locally instructions on the Heroku Facebook Developers page, which I highly recommend you do as well, to make a local development environment.

In short, you’ll need to create a second application (just a “Website” app this time) and install the Foreman gem (gem install foreman) Once you have Foreman installed, create your .env file, per the instructions, and type foreman start from the root of your app. The local, development version of Stalker will now be running at http://127.0.0.1. Well, it’s still just the example application, but we are just a few steps from our own app.

First, we’ll change our root handler to create a @friend instance variable:

get "/" do
  redirect "/auth/facebook" unless session[:at]
  @client = Mogli::Client.new(session[:at])

  # limit queries to 15 results
  @client.default_params[:limit] = 15

  @app  = Mogli::Application.find(ENV["FACEBOOK_APP_ID"], @client)
  @user = Mogli::User.find("me", @client)
  # Randomly pick a friend
  @friend = @user.friends(:name, :gender, :hometown,:birthday).sort_by {rand}.first unless @friend
  erb :index
end

We are grabbing a random friend and asking for the fields we want to show. See where we ask for hometown and birthday? We can do that because we asked for those fields when we authorized the application.

Now, modify the index.erb file. I am just including a part of the change, where I print out some information about the friend.

<h1>Is THIS what you wanna know, sicko?</h1>
<ul>
  <li><em>Name: </em> <%=@friend.name%></li>
  <li><em>Gender: </em> <%=@friend.gender%></li>
  <li><em>Hometown: </em> <%=@friend.hometown%></li>
  <li><em>Birthday: </em> <%=@friend.birthday%></li>
</ul>
</section>

You might want to change or add any CSS styles to the site, as I did. I took out the various background images in base.css and changed the background color of the top banner. It’s not going to win any design awards, but with a name like “Stalker” it was probably out of the running already. Here is my new screen.css:

@import url("https://statics.Herokuapp.com/fonts/fonts.css");
@import url("reset.css");
@import url("base.css");

a {
  color:#FFF;
}
#get_started a:visited {
  color:#fff;
}

Here is an image of the app in development:

All we have to do now is push this to Heroku. This is where Heroku shines, pulling the infrastructure concerns out of the way of the developer. Deployment is unthinkably simple:

git commit -am "Basic Stalking in place. BWAAHAHAHA"
git push Heroku

And now, anyone that wants to randomly stalk their friends on Facebook can do so with your awesome Stalker app. And you can focus on adding more features to the app, because you don’t have to worry about how it’s hosted, how it will scale, or what you will do with your millions.

Get to it.

Hopefully, you now have a good idea how to use Heroku’s new integration with Facebook development along with Ruby to make your Social App Developer name!

You can obviously do much more with a Facebook application than Stalker does. I’m sure that we will see many more examples and posts about this new integration in the next few weeks. I’d love to hear what you think of this new hotness, as well as what questions you have. The people at Heroku are excited to get developers busy with Facebook development, so get to it.

Resources

Heroku Annoucement
Facebook Annoucement
Heroku: Getting Started with your Facebook App
Facebook Developer Documentation

SitePoint Content Partner

This tutorial has been made possible by the support of SFDC. In cooperation with SFDC and independently written by SitePoint, we strive to work together to develop the content that’s most useful and relevant to you.

Glenn GoodrichGlenn Goodrich
View Author

Glenn works for Skookum Digital Works by day and manages the SitePoint Ruby channel at night. He likes to pretend he has a secret identity, but can't come up with a good superhero name. He's settling for "Roob", for now.

Heroku
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week