Setting Up Your Application to Use Bundler


Bundler makes sure that Ruby can find all of the gems in the Gemfile (and all of their dependencies).

For another kind of application (such as a Sinatra application/Ruby app), you will need to set up bundler before trying to require any gems. At the top of the first file that your application loads , put the following code:

require "rubygems"
require "bundler/setup"

This will automatically discover your Gemfile, and make all of the gems in your Gemfile available to Ruby (in technical terms, it puts the gems “on the load path”). You can think of it as an adding some extra powers to require "rubygems".

Now that your code is available to Ruby, you can require the gems that you need. For instance, you can require "nokogiri". If you have a lot of dependencies, you might want to say “require all of the gems in my Gemfile“. To do this, put the following code immediately following require "bundler/setup":
Bundler.require(:default)

 

Using Bundler with Rails 2.3


1. Insert the following code in config/boot.rb, right above the line `Rails.boot!`

class Rails::Boot
  def run
    load_initializer

    Rails::Initializer.class_eval do
      def load_gems
        @bundler_loaded ||= Bundler.require :default, Rails.env
      end
    end

    Rails::Initializer.run(:set_load_path)
  end
end

2.Create a new file, config/preinitializer.rb, and insert the following.

begin
  require "rubygems"
  require "bundler"
rescue LoadError
  raise "Could not load the bundler gem. Install it with `gem install bundler`."
end

if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24")
  raise RuntimeError, "Your bundler version is too old for Rails 2.3." +
   "Run `gem install bundler` to upgrade."
end

begin
  # Set up load paths for all bundled gems
  ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)
  Bundler.setup
rescue Bundler::GemNotFound
  raise RuntimeError, "Bundler couldn't find some gems." +
    "Did you run `bundle install`?"
end
That's it :)