Sinatra And Bundler
I’ve been working with Rails 3 a lot lately and that work has led to a healthy appreciation for bundler. So much so, I figured it would be a good idea to update this site (a sinatra app) to work with bundler. The changes were pretty trivial in contrast to all the control you get from using bundler.
Here’s a quick rundown of what you need to do to get sinatra and bundler working together.
First thing you need is a Gemfile.
# Gemfile
source 'http://rubygems.org'
gem 'haml', '3.0.12'
gem 'RedCloth', '4.2.3'
gem 'sinatra', '1.0', :require => false
group :test do
gem 'rack-test', '0.5.4'
gem 'rspec', '1.3.0'
end
Notice that the sinatra gem is set to :require => false. This is Important to keep your existing app functioning properly.
Next I added a bundler_helper.rb file to my lib directory to do all the auto require magic.
# Bundler Helper
require 'rubygems'
require 'bundler'
Bundler.setup unless File.exists?(File.expand_path('../.bundle/environment', __FILE__))
Bundler.require(:default)
Now you can remove all the require calls for external gems inside your app file. Well, everything but the line that requires sinatra. The first five lines of my sinatra app now looks like this:
# add lib dir to load path
$:.unshift File.join(File.expand_path(File.dirname(__FILE__)), 'lib')
require 'bundler_helper'
require 'sinatra'
After that, it’s pretty much bundler business as usual.