Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for Ruby Gem availability

Is there a way to check if some gem is currently installed, via the Gem module? From ruby code, not by executing 'gem list'...

To clarify - I don't want to load the library. I just want to check if it's available, so all the rescue LoadError solutions don't help me. Also I don't care if the gem itself will work or not, only whether it's installed.

like image 555
viraptor Avatar asked Jun 23 '09 11:06

viraptor


People also ask

How do you check gems in Ruby?

The Gem command is included with Ruby 1.9+ now, and is a standard addition to Ruby pre-1.9. Because local_gems relies on group_by , it returns a hash of the gems, where the key is the gem's name, and the value is an array of the gem specifications.

How do you check if gem is installed or not?

Since your goal is to verify a gem is installed with the correct version, use gem list . You can limit to the specific gem by using gem list data_mapper . To verify that it's installed and working, you'll have to try to require the gem and then use it in your code.

How do I check if I have the latest version of gems?

Using gem, the closest I can get is gem list -d [gemname] , which appears to list only the latest version installed.

Where do RubyGems get installed?

When you use the --user-install option, RubyGems will install the gems to a directory inside your home directory, something like ~/. gem/ruby/1.9. 1 . The commands provided by the gems you installed will end up in ~/.


2 Answers

In Ruby 1.9.3 only there is also:

Gem.available?('somegem') 

You can use regex expressions too. Handy if I want to allow 'rcov' and GitHub variants like 'relevance-rcov':

Gem.available?(/-?rcov$/) 
like image 109
foz Avatar answered Sep 20 '22 12:09

foz


Looking at the Gem API documentation, using Gem::Specification::find_all_by_name to test for gem availability seems reasonable.

if Gem::Specification::find_all_by_name('gemname').any?   do stuff end 

find_all_by_name always returns an array (of Specification objects), as opposed to find_by_name which raises an exception if no match is found.

like image 31
Eric Drechsel Avatar answered Sep 20 '22 12:09

Eric Drechsel