如何从ruby脚本中安装rubygem并在之后需要这个gem?

时间:2015-02-22 09:43:02

标签: ruby gem rubygems

我想做这样的事情:

begin
  require 'progressbar'
rescue LoadError => e
  puts "exception .. installing with gem"
  h = system 'gem install progressbar'
  puts "gem installed #{h}"
  require 'progressbar'
end
pbar = ProgressBar.new("test", 100)
100.times {sleep(0.1); pbar.inc}; pbar.finish

但很明显,如果您运行此代码段,则无法使用进度条宝石。

1 个答案:

答案 0 :(得分:2)

我发现了这个讨论:https://www.ruby-forum.com/topic/131346 显然,调用Gem.clear_paths可以解决问题。总计:

begin
  require 'progressbar'
rescue LoadError => e
  puts "exception .. installing gem"
  h = system 'gem install progressbar'
  puts "gem installed #{h}"
  Gem.clear_paths
  require 'progressbar'
end
pbar = ProgressBar.new("test", 100)
100.times {sleep(0.1); pbar.inc}; pbar.finish