Ruby 以编程方式安装 gem

Ama*_*mal 3 ruby rubygems

如果我在脚本中使用反引号以编程方式安装 gem,gem install gem_name如下所示:

if not_gem_installed
  `gem install my_gem`
end

require 'my_gem'
Run Code Online (Sandbox Code Playgroud)

然后需要宝石,aLoadError出现。有任何解决这个问题的方法吗?

Sun*_*dan 5

我尝试过使用反引号安装 gem,发现我遇到了与问题中提到的相同的问题。我发现这不是这项工作的最佳选择。我建议使用 Gem 来搜索 gem 和安装。

require 'rubygems/commands/install_command'

def find_or_install(gem_name)
  Gem::Specification::find_by_name(gem_name)
rescue Gem::LoadError
  install_gem(gem_name)
end

def install_gem(gem_name)
  cmd = Gem::Commands::InstallCommand.new
  cmd.handle_options [gem_name]     

  cmd.execute
rescue Gem::SystemExitException => e
  puts "FAILURE: #{e.exit_code}"
end
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/adamjmurray/3154437 - 要点与很好的例子