2013-09-25 39 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 
相關問題