本文介绍了检查Ruby Gem的可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过Gem模块来检查当前是否安装了一些gem?从ruby代码中,不是执行'gem list'...

澄清 - 我不想加载库。我只是想检查它是否可用,因此所有的救援LoadError 解决方案都不能帮助我。我也不在乎宝石本身是否会起作用,只是它是否已安装。

解决方案

恕我直言,最好的办法是尝试加载/需要创业板,并拯救该例外,正如雷已经表明的那样。解决LoadError异常是安全的,因为它不是由GEM本身引发的,而是它的标准行为。



您也可以使用gem命令。 / p>

 开始
gemsomegem
#需求
gemsomegem,> ; = 2.0
rescue Gem :: LoadError
#未安装
结束

gem命令与require命令具有相同的行为,但略有不同。 AFAIK,它仍会尝试自动加载主要的GEM文件。



挖掘rubygems.rb文件(第310行),我发现以下代码执行:

  matches = Gem.source_index.find_name(gem.name,gem.version_requirements)
report_activate_error(gem)if matches.empty?

它可以为您提供一些关于如何在不实际加载库的情况下进行脏检查的提示。 p>

Is there a way to check if some gem is currently installed, via the Gem module? From ruby code, not by executing 'gem list'...

To clarify - I don't want to load the library. I just want to check if it's available, so all the rescue LoadError solutions don't help me. Also I don't care if the gem itself will work or not, only whether it's installed.

解决方案

IMHO the best way is to try to load/require the GEM and rescue the Exception, as Ray has already shown. It's safe to rescue the LoadError exception because it's not raised by the GEM itself but it's the standard behavior of the require command.

You can also use the gem command instead.

begin
  gem "somegem"
  # with requirements
  gem "somegem", ">=2.0"
rescue Gem::LoadError
  # not installed
end

The gem command has the same behavior of the require command, with some slight differences. AFAIK, it still tries to autoload the main GEM file.

Digging into the rubygems.rb file (line 310) I found the following execution

matches = Gem.source_index.find_name(gem.name, gem.version_requirements)
report_activate_error(gem) if matches.empty?

It can provide you some hints about how to make a dirty check without actually loading the library.

这篇关于检查Ruby Gem的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:02
查看更多