Bundler: how to use without rails?

2019-04-18 07:11发布

问题:

I have a project using cucumber outside of rails. How can I load the gems with the versions specified in my gemfile?

回答1:

Digging through the Bundler website:

  1. Create Gemfile (run bundle init to create skeleton Gemfile)
  2. bundle install
  3. In your app:

    # Only needed for ruby 1.8.x
    require 'rubygems'
    
    # The part that activates bundler in your app
    require 'bundler/setup' 
    
    # require your gems as usual
    require 'some_gem'
    
    # ...or require all the gems in one statement
    Bundler.require
    

Could be worth checking out:

Bundler.io - Using Bundler in Your Appplication
Bundler.io - Bundler.setup and Bundler.require

Are bundle exec and require 'bundler/setup' equivalent?



回答2:

I just learned about a way to make Bundler automatically require dependencies from a Gemfile. Add this code at the beginning of a Ruby program that has a Gemfile:

require 'rubygems'
require 'bundler/setup'
Bundler.require

With Bundler.require there's no need to explicitly require the gems/libraries enumerated in the Gemfile.

This solution is from http://technotales.wordpress.com/2010/08/22/bundler-without-rails/

To be honest I'm not sure if the require rubygems part is needed either.



回答3:

Here's the simplest and most straightforward approach:

  1. bundler init will create the Gemfile for you
  2. Specify gems in the Gemfile.
  3. Add the following to your main Ruby file
require 'bundler/setup'
Bundler.require
  1. Run bundler install to install the gems.

More information can (now) be found at http://bundler.io.



回答4:

Casper has a pretty good answer (despite some passive aggressiveness) but I think the missing piece for you is bundle exec. When you run the $ rails ... commands on the command line, Rails uses bundler to load those dependencies/gems. Rake, for example, doesn't by default so in order to run rake test using an older version of cucumber than what is on your system, you have to use bundle exec rake test. It's a good habit to get into always using $ bundle exec ... when you're using Bundler — it's explicit, you're always sure you're using the right gems, and it ensures you don't forget to add a dependency to your Gemfile (i.e. you push to another server or another developer and they are having issues because you didn't note the need for something you use but they don't).