Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install Ruby gem automatically, if required?

Tags:

ruby

rubygems

Given a Ruby program that uses a particular gem (e.g. term-ansicolor), how could I install the gem automatically, if required?

In other words, the program does:

require 'term/ansicolor'

and, in case the gem wasn't install previously, I would like to install it and continue the program rather than getting an error:

LoadError: no such file to load -- term/ansicolor
from (irb):1:in `require'
from (irb):1
from :0

What would be the most appropriate method to achieve that?

like image 608
Misha Moroshko Avatar asked Nov 21 '25 10:11

Misha Moroshko


2 Answers

I've been using this pattern:

require 'rubygems'
begin
  gem 'minitest'
rescue Gem::LoadError
  Gem.install('minitest')
  gem 'minitest'
end
require 'minitest'
like image 192
thomthom Avatar answered Nov 24 '25 02:11

thomthom


Such a tool is not available. Read a detailed discussion about it here http://www.ruby-forum.com/topic/2728297

like image 30
Rishav Rastogi Avatar answered Nov 24 '25 04:11

Rishav Rastogi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!