首页 > 解决方案 > Rails 在 shell 中执行的文件的 gem 必须在 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

提前致谢

标签: ruby-on-railsrubygems

解决方案


bundle exec - 脱壳

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

Bundler.with_clean_env do
  `brew install wget`
end

推荐阅读