要求卸载的gem不会在开始救援中“救援”

时间:2019-10-06 03:16:30

标签: ruby rubygems

我在这里处理一个非常小的问题。我只是试图要求一些gem,如果未安装gem,仅恢复到rescue块中的代码。但是,即使它位于rescue / begin块中,也永远不会到达rescue

begin
  ['net/http', 'getopt/std', 'pry','json'].each(&method(:require))
rescue
  puts "A gem required for this script is missing. It is installing now."
  `gem install getopt`
  ['net/http', 'getopt/std'].each(&method(:require))
end

当我在没有安装第一个gem net/http的系统上运行此脚本时,会出现以下错误:

Traceback (most recent call last):
    2: from ./agent.rb:16:in `<main>'
    1: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- getopt/std (LoadError)

这不是应该进入救援营地吗?我做错了什么导致它没有进入救援区?

1 个答案:

答案 0 :(得分:0)

在这里找到答案:How to rescue from a require "gem_name" when the gem is not installed

只需将rescue更改为rescue LoadError,就可以解决此问题。无论出于什么原因,我都认为只包含rescue而后不包含任何内容将会捕获 all