Tuesday, February 15, 2011

Using Sinatra with Bundler to deploy on Heroku

I decided to try using sinatra for a small project I started the other day. I normally work in rails and host my personal projects on heroku. Since rails 3 came out I have also gotten hooked on bundler. I could not find any single source that documented how to use all of these together nicely. Here is how I got it to work.

Gemfile

The gemfile is pretty basic, set a source for gems and include the sinatra gem.
source :rubygems
gem 'sinatra'

config.ru

This is the rackup config file which sets the app up to run in rack.
require 'rubygems'
require 'bundler'

Bundler.require

require './myapp'

run MyApp

myapp.rb

This is the sinatra file. Note that I defined a class (MyApp). This is very important because our config.ru needs the class as a handle for the 'run MyApp' call. An alternative would be to use "run Sinatra::Application" in your config.ru file.
class MyApp < Sinatra::Base
  get '/' do
    'Hello world!'
  end
end

Running locally

First make sure rack is installed, then run the following commands in the root folder and the app should be up and running locally.
bundle install
rackup

Deploying to Heroku

Just run the following commands in the root folder and the app should be up and running on Heroku.
git init
git add .
git commit -m 'Initial version of MyApp'
heroku create
git push heroku master

Additional resources