[フレーム]
Last Updated: February 25, 2016
·
1.529K
· prathamesh-sonpatki

Install a gem automatically if it's not installed

I have faced a problem of Gem::LoadError while using same .irbrc with different rubies. Especially when a new ruby version is installed. If i require some gems in .irbrc, i get the error 'cannot load such file --'. To counter this, if a gem is not present, there should be a way to install it and reload the path.
Following snippet of code does just that.

# Check for presence of required gems. 
# If not present, install the gems
["wirble", "awesome_print"].each do |gem|

 begin
 gem "#{gem}"
 rescue Gem::LoadError
 `gem install #{gem}`
 Gem.clear_paths
 end

end

Now after this code you can safely require wirble or awesome_print, without worrying whether it is installed on your system or not.

AltStyle によって変換されたページ (->オリジナル) /