ruby-on-rails - rake 任务在另一个项目中执行 bundle 安装

标签 ruby-on-rails ruby bash rake bundle

如何编写 rake 任务来在不同的项目中运行 bundle 安装?我已经创建了一个仅使用 rake 的项目,并编写了这样的任务

task :bundle do
  projects.each do |name, repo|
    if Dir.exists?("../#{name}")
      exec("cd ../#{name} && bin/bundle install")
    end
  end
end

但是当我运行这个时,我得到:

Using rake 10.3.2
Using bundler 1.9.6
Bundle complete! 1 Gemfile dependency, 2 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

乍一看没问题,但实际上是当前仅 rake 项目而不是目标 Rails 项目的 bundle 安装

我也尝试过反勾

puts `cd ../#{name} && bin/bundle install`

但它也做了同样的事情。我还尝试了 bundle install 而不是 bin/bundle install,但它不起作用。

当我直接在命令上运行它时,它会按照我的预期运行:

Using rake 10.4.2
Using CFPropertyList 2.3.1
...
...
Using turbolinks 2.5.3
Using uglifier 2.7.1
Bundle complete! 34 Gemfile dependencies, 120 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

如何让它进行正确的 bundle 安装

最佳答案

对此需要注意的几点

bin/bundle 仅当 bundle 文件存在于 bin 目录中时才有效

  • 有多种不同的方法可以在 shell 中执行命令
    • exec('echo "Hello World"') - 运行命令并用它替换当前进程。
    • system('echo "Hello World"') - 在子 shell 中运行命令并捕获退出状态代码
    • `echo "hello world"` - 在子 shell 中运行命令并捕获 STDOUT 和 STDERR 的所有输出,但不捕获退出状态代码。

为什么它不起作用

您需要为 bundle 程序提供一个干净的环境,以便它知道您正在 bundle 不同的项目。使用 Bundler.with_clean_env block 将 rake 任务中的命令包围起来,如下所示

task :bundle do
  Bundler.with_clean_env do
    projects.each do |name, repo|
      if Dir.exists?("../#{name}")
        exec("cd ../#{name} && bundle install")
      end
    end
  end
end

关于ruby-on-rails - rake 任务在另一个项目中执行 bundle 安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147436/

相关文章:

php- 命令不适用于 php shell_exec

ruby-on-rails - "where"和 "find"之间的区别

javascript - 计算表单中嵌套字段集的数量

ruby-on-rails - 当 Ruby 显示类似 : #<Role:0x11157b630>? 的内容时发生了什么

ruby-on-rails - bcrypt-ruby 3.1.2 Gem::Ext::BuildError: 错误: 无法在 OSX 中构建 gem native 扩展

bash --debugger 在安装 bashdb 后无法在没有参数的脚本上使用 bash 4.3

linux - 如何将当前目录中的文件添加到数组中

ruby-on-rails - Rails 4 - CarrierWave default_url 不适用于 Assets 图像

ruby-on-rails - rails Carrierwave 和 s3 : wrong number of arguments (2 for 1)

ruby-on-rails - 如何使用 Rails 缓存来存储 Nokogiri 对象?