检查 Ruby Gem 的可用性 [英] Check for Ruby Gem availability

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

问题描述

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

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

澄清一下 - 我不想加载库.我只是想检查它是否可用,所以所有 rescue LoadError 解决方案都对我没有帮助.另外,我不在乎 gem 本身是否可以工作,只在乎它是否已安装.

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.

推荐答案

恕我直言,最好的方法是尝试加载/请求 GEM 并挽救异常,正如 Ray 已经展示的那样.挽救 LoadError 异常是安全的,因为它不是由 GEM 本身引发的,而是 require 命令的标准行为.

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.

您也可以使用 gem 命令代替.

You can also use the gem command instead.

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

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

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.

挖掘 ruby​​gems.rb 文件(第 310 行)我发现了以下执行

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 的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆