How to find out if a gem is installed in the system or not?

How to find out if a gem is installed in the system?

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

Is there a shorter method?

+4
source share
4 answers

If you are trying to do this from ruby, you can use the built-in RubyGem method. Older versions provide the Gem.available?('capybara') method, which returns a boolean, but this is deprecated. The recommended method is now to use (provided that you use a version that supports it):

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

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

Update

If you need a boolean result, you can 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 
+15
source
 %x('gem' 'list' | 'grep' 'capybara').empty? 
+3
source

I insert 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 beautifully!

+3
source

Here is the code that works for me. It also correctly handles Gem::LoadError , which is thrown when you try to load a gem that cannot 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') 
+1
source

Source: https://habr.com/ru/post/1386106/


All Articles