After installing a gem within a script, how do I load the gem?

后端 未结 4 429
再見小時候
再見小時候 2021-02-04 07:36

I have a small Ruby script that I\'m writing to automate the preparation of a development environment on local machines. Because I can\'t be certain that the rubyzip2

4条回答
  •  礼貌的吻别
    2021-02-04 08:29

    Ok so you may want to use Bundler and set up a Gemfile then have bundler do a bundle install, bundler will fetch out all the gems and install them if it is not already installed and you can then require all the gems in the gem file. Read the documentation in the link for more information.

    But what you are looking to do specifically in your question is to use the retry keyword. This keyword will retry the loop after the rescue was called.

    So if you require the gem and it fails and the Load Error Exception is called. The Begin Block will rescue, the system call will install the gem, then it will retry and require the gem. Just cautious because this may lead to an infinite loop unless you want to set up a condition to maybe retry it only once.

    begin
      require 'zip/zip'
    rescue LoadError
      system("gem install rubyzip2")
      retry
    end
    

提交回复
热议问题