snax

developing a facebook app locally

In which we host a Facebook/Rails app on our local machine and avoid the deploy/test cycle.

code

Make a file config/facebook.yml to hold your settings:

---
development:
  your_username:
    facebook:
      key: 08192fc4c5916a75f3014c130ab241073
      secret: 62c551acccde773e011456957aab0f6f
    port: 10000
  developer_twos_username:
    facebook:
      key: ""
      secret: ""
    port: 10001
  host: yourapp.yourserver.com

No, those aren’t my real keys. But you get the idea.

Now, add to config/environment.rb:

FACEBOOK_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/facebook.yml")[RAILS_ENV]
FACEBOOK_CONFIG.merge!(FACEBOOK_CONFIG[ENV['USER']] || {})

This lets individual developers override any global setting by adding the key under their username.

Now, install this rake task in lib/tasks/tunnel.rake:

namespace "tunnel" do
  desc "Start a reverse tunnel from FACEBOOK_CONFIG['host'] to localhost"
  task "start" => "environment" do
    puts "Tunneling #{FACEBOOK_CONFIG['host']}:#{FACEBOOK_CONFIG['port']} to 0.0.0.0:3000"
    exec "ssh -nNT -g -R *:#{FACEBOOK_CONFIG['port']}:0.0.0.0:3000 #{FACEBOOK_CONFIG['host']}"
  end

  desc "Check if reverse tunnel is running"
  task "status" => "environment" do
    if `ssh #{FACEBOOK_CONFIG['host']} netstat -an |
        egrep "tcp.*:#{FACEBOOK_CONFIG['port']}.*LISTEN" | wc`.to_i > 0
      puts "Seems ok"
    else
      puts "Down"
    end
  end
end

The rake task opens an SSH connection to our server and forwards a port on it to our local box. This will work no matter what kind of NAT or proxy you are behind, as long as you can access your server via SSH.

server setup

Your server’s /etc/ssh/sshd_config file must contain the following line:

GatewayPorts clientspecified

facebook setup

Have each developer setup a Facebook app for themselves, and set the callback url to be their port on your server:

usage

Now, whatever computer you are on, just run rake tunnel:start and Facebook will be able to see your local machine on port 3000. Check that it’s up with rake tunnel:status.

If you’re on an unreliable network, you may want to make a cronjob to keep the tunnel alive.

further resources

Not many people are discussing how to develop a Facebook/Rails app in a sane way, so I might make a series of these “best practice”-style things. The best resources right now are:

Liverail also has a tutorial, but it assumes you know nothing about Rails, so it’s kind of a drag.