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
library is present on all of the machines, I'm having the script install it when needed.
Currently, my script is doing the following:
begin
require 'zip/zip'
rescue LoadError
system("gem install rubyzip2")
end
Once the gem has been installed, the script continues execution; however, the gem hasn't been loaded so all code requiring rubyzip2
halts the execution.
How do I load the gem into memory so that the script can continue running after installation?
run the command bundle install in your shell, once you have your Gemfile created. This command will look your Gemfile and install the relevant Gems on the indicated versions. The Gemfiles are installed because in your Gemfile you are pointing out the source where the gems can be downloaded from.
The Gemfile is wherever you want it to be - usually in the main directory of your project and the name of the file is Gemfile . It's convenient to have one because it allows you to use Bundler to manage which gems and which versions of each your project needs to run.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With