2013-09-25 41 views
1

如果在计算机上安装了磁带库/宝石"foo"并且可用,是否有方法可以检查而不引发(并挽救)错误?检查计算机上是否安装了磁带库

也许,ruby-gemsbundler应该在源代码中有一些相关的代码,但我无法发现它。

+0

'宝石列表foo',还是你的意思是从在一个程序内? – matt

+0

@matt是的。从Ruby内部。 – sawa

回答

1

我看到了有关source。我可以这样做:

  • 检查整个负载路径:

    Gem.find_files("foo").any? 
    
  • 检查只有宝石:

    Gem.find_files("foo", false).any? 
    
0

如果您已经安装了pry,那么你可以做如下使用方法Pry::Rubygem.installed?

[email protected]:~$ 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)> 

或者你可以如下操作:

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 
相关问题