Misha Moroshko
Misha Moroshko

Reputation: 171479

How to install Ruby gem automatically, if required?

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?

Upvotes: 2

Views: 4391

Answers (4)

thomthom
thomthom

Reputation: 2914

I've been using this pattern:

require 'rubygems'
begin
  gem 'minitest'
rescue Gem::LoadError
  Gem.install('minitest')
  gem 'minitest'
end
require 'minitest'

Upvotes: 4

Eugene
Eugene

Reputation: 4879

Alternatively, you could build your package into a gem and put the required gem as a dependency in the gemspec. It would then get installed automatically when you install the gem.

Upvotes: 1

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

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

Upvotes: 3

lucapette
lucapette

Reputation: 20724

You should consider to use bundler. It's the de-facto standard way to manage dependencies in Ruby software.

Upvotes: 3

Related Questions