Rails 在 shell 中执行的文件的 gem 必须在 Gemfile 中

The gems of the files executed in a shell by Rails have to be in Gemfile

如果我 运行 来自 rails 的脚本并且该脚本需要在 Gemfile 中找不到的 gem 它不起作用,但是执行的脚本与Rails 的行为应该与您执行任何其他操作一样,例如 ls

示例:/tmp/fichero.rb

     #! /usr/bin/env ruby
     #encoding: utf-8

     require "rubygems"
     require 'choice'
     require 'fileutils'
     ...
     ...

宝石文件

    ...
    ...
    #gem 'choice'
    ...
    ...

控制器:

    stmt = "ruby /tmp/fichero.rb -p hola"
    stdout, stderr, status = Open3.capture3(stmt)

    stmt = "ruby /tmp/fichero.rb -p hola"
    %x[#{stmt}]

两者:

`require': 无法加载这样的文件 -- 选择 (LoadError)

如果我更改 Gemfile:

    ...
    ...
    gem 'choice'
    ...
    ...

它可以工作,但我不想在我的 Gemfile

中使用这个 gem

提前致谢

bundle exec - Shelling-out

任何 Ruby 打开子 shell 的代码(如系统、反引号或 %x{})将自动使用当前的 Bundler 环境。如果您需要 shell 输出到不属于当前包的 Ruby 命令,请使用带有块的 with_clean_env 方法。在块内创建的任何子shells 将被赋予在 Bundler 被激活之前存在的环境。例如,Homebrew 命令 运行 Ruby,但不能在包内工作:

Bundler.with_clean_env do
  `brew install wget`
end