Reputation: 168259
Is there a way to check without raising (and rescuing) an error if a library/gem "foo"
is installed on the computer and is available?
Probably, ruby-gems
or bundler
should have some relevant code in the source, but I cannot spot it.
Upvotes: 1
Views: 292
Reputation: 168259
I spotted the relevant source. I can do:
Checking the entire load path:
Gem.find_files("foo").any?
Checking for only gems:
Gem.find_files("foo", false).any?
Upvotes: 1
Reputation: 118299
If you have installed the pry,then you can do as below using the method Pry::Rubygem.installed?
:
kirti@kirti-Aspire-5733Z:~$ irb
2.0.0p0 :001 > require 'pry'
=> true
2.0.0p0 :002 > pry
[1] pry(main)> Pry::Rubygem.installed?('nokogiri')
=> true
[2] pry(main)> Pry::Rubygem.installed?('foo')
=> false
[3] pry(main)>
Or you can do as below:
require 'rubygems'
def installed?(name)
if Gem::Specification.respond_to?(:find_all_by_name)
Gem::Specification.find_all_by_name(name).any?
else
Gem.source_index.find_name(name).first
end
end
installed?('nokogiri') # => true
installed?('foo') # => false
Upvotes: 0