【发布时间】:2011-08-09 16:29:51
【问题描述】:
我有一个项目在铁轨外使用黄瓜。如何使用我的 gemfile 中指定的版本加载 gem?
【问题讨论】:
我有一个项目在铁轨外使用黄瓜。如何使用我的 gemfile 中指定的版本加载 gem?
【问题讨论】:
Gemfile(运行bundle init创建骨架Gemfile)bundle install在您的应用中:
# 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
Bundler.io - Using Bundler in Your Appplication
Bundler.io - Bundler.setup and Bundler.require
【讨论】:
我刚刚了解了一种使 Bundler 自动需要 Gemfile 的依赖项的方法。在具有 Gemfile 的 Ruby 程序的开头添加以下代码:
require 'rubygems'
require 'bundler/setup'
Bundler.require
使用 Bundler.require,无需显式要求 Gemfile 中枚举的 gem/库。
此解决方案来自http://technotales.wordpress.com/2010/08/22/bundler-without-rails/
说实话,我也不确定是否需要 require rubygems 部分。
【讨论】:
require 'rubygems' 仅在 1.8.7 之前的 Ruby 中需要,如果我没记错的话。
这是最简单最直接的方法:
bundler init 将为您创建 Gemfilerequire 'bundler/setup'
Bundler.require
bundler install 安装gem。更多信息(现在)可以在http://bundler.io找到。
【讨论】:
Casper 有一个很好的答案(尽管有一些被动的攻击性),但我认为你缺少的部分是 bundle exec。当您在命令行上运行$ rails ... 命令时,Rails 使用捆绑程序来加载这些依赖项/gems。例如,Rake 默认情况下不支持,因此要使用比系统上旧版本的黄瓜运行 rake test,您必须使用 bundle exec rake test。当您使用 Bundler 时,始终使用 $ bundle exec ... 是一个好习惯 - 这是明确的,您始终可以确定您使用的是正确的 gem,并确保您不会忘记向您的 Gemfile 添加依赖项(即,您推送到另一台服务器或另一位开发人员,但他们遇到了问题,因为您没有注意到您需要使用的东西,但他们没有)。
【讨论】:
require "bundler/setup" 也需要bundle exec。 IE。 bundle exec 是否只是为了确保即使没有设置也能正常工作?
$ bundle exec ruby foo.rb 即可。
bundler/setup“强制”为红宝石(除其他外)。所以使用bundle exec 是一种额外的保险,一切都将真正使用bundler 运行。它还可以轻松地以这种方式捆绑旧应用程序(或任何应用程序),并且您不必接触任何代码。