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

后端 未结 4 579
再見小時候
再見小時候 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:30

    Instead of doing require 'thegem' and rescuing error, you should check the gem availability before, and then, if needed, install it. After, you can require it.

    Take a look at this post for the gem availability

    Or this post

    EDIT

    After installation, you need to clear gem paths if you don't want to reload your script. You could achieve this with this method :

    Gem.clear_paths
    

    There are already answered questions here

    So your code should looks like this ( for example ) :

    begin
      gem "rubyzip2"
    rescue LoadError
      system("gem install rubyzip2")
      Gem.clear_paths
    end
    
    require 'zip/zip'
    

提交回复
热议问题