pankajdoharey
pankajdoharey

Reputation: 1572

How do I find out whether a gem is installed in the system or not?

How do I find out whether a gem is installed in the system or not?

%x('gem' 'list').split.find{|i| i == "capybara"}

Is there a shorter method?

Upvotes: 4

Views: 2906

Answers (4)

Peter Brown
Peter Brown

Reputation: 51717

If you're trying to do this from within ruby, you can use a built-in RubyGem method. Older versions provide a Gem.available?('capybara') method that returns a boolean, but this has been deprecated. The recommended way now is to use (assuming you're using a version that supports it):

Gem::Specification::find_by_name('capybara')

http://rubygems.rubyforge.org/rubygems-update/Gem/Specification.html

Update

If you want a boolean result, you could use .find_all_by_name() and check if the resulting array is empty:

if Gem::Specification::find_all_by_name('capybara').any?
  # Gem is available
end

Upvotes: 15

Peter Krnjevic
Peter Krnjevic

Reputation: 1120

I stick this at the beginning of my Gemfile:

def gem_available?(gemname)
  if Gem::Specification.methods.include?(:find_all_by_name) 
    not Gem::Specification.find_all_by_name(gemname).empty?
   else
     Gem.available?(gemname)
   end
 end

then just use:

if (gem_available?('gem_i_need'))

and everything works nicely!

Upvotes: 3

Dylan Northrup
Dylan Northrup

Reputation: 161

Here's some code that works for me. It also properly handles the Gem::LoadError that gets thrown when you try to load a gem that could not be found.

require 'rubygems'

def can_we_find_gem(gem_name)
  found_gem = false
  begin
    found_gem = Gem::Specification.find_by_name(gem_name)
  rescue Gem::LoadError
    puts "Could not find gem '#{gem_name}'"
  else
    puts "Found gem '#{gem_name}'"
  end
end

can_we_find_gem('chef')
can_we_find_gem('not-chef')

Upvotes: 1

clyfe
clyfe

Reputation: 23770

%x('gem' 'list' | 'grep' 'capybara').empty?

Upvotes: 3

Related Questions