Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install gem on demand

Tags:

ruby

rubygems

gem

I would like to install a gem (JSON) on the client side, but only if hasn't been installed already (some 1.9 Ruby distros have JSON bundled).

I couldn't find a clue on how to do that from gem help install. And running gem install json on a Windows system with Ruby 1.9 installed (with JSON bundled) results in

    ERROR:  Error installing json:
    The 'json' native gem requires installed build tools.

-- it tries to install it ignoring the fact that the gem is already there.

And I can't do bash tricks like grepping gem list output because the client might be Windows.

So what's the multiplatform way of installing a gem only if it's not present in the system already?

like image 328
Oleg Mikheev Avatar asked Apr 04 '12 09:04

Oleg Mikheev


People also ask

Why bundle install is installing gems in vendor bundle?

In deployment, isolation is a more important default. In addition, the user deploying the application may not have permission to install gems to the system, or the web server may not have permission to read them. As a result, bundle install --deployment installs gems to the vendor/bundle directory in the application.

How do I install a specific version of a gem?

Use `gem install -v` You may already be familiar with gem install , but if you add the -v flag, you can specify the version of the gem to install. Using -v you can specify an exact version or use version comparators.


1 Answers

This may work...

begin
  require "json"
rescue LoadError
  system("gem install json")
end

If you don't want to require "json", you can remove it from $LOAD_PATH.

Or, put as a one liner:

ruby -e 'begin; require "some_gem"; rescue LoadError; system "gem install some_gem"; end'
like image 162
Tomato Avatar answered Oct 02 '22 05:10

Tomato