Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

gem

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?

like image 575
Tom Avatar asked Feb 21 '12 20:02

Tom


People also ask

How do I run a gem file?

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.

Where is the gem file?

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.


1 Answers

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'
like image 62
louiscoquio Avatar answered Sep 19 '22 20:09

louiscoquio