以编程方式检查捆绑中的宝石? [英] Programmatically check if gem in bundle?

查看:110
本文介绍了以编程方式检查捆绑中的宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时,捆绑器安装完成并应用后,什么是以编程方式检查给定 gem_name 是否在捆绑包中的最佳方式?

通过阅读源代码,我发现了 Bundler.definition
$ p $ gem_name ='banana'
Bundler.definition.dependencies.map($ c $
),例如 &:name).include?(gem_name)

但无法找到文档 1 ,我不知道这是否是推荐用法。



更新:它看起来像 Bundler :: Definition#dependencies code>返回所有依赖关系,而不考虑组。作为替代,我发现了 Bundler :: Runtime#dependencies_for ,它以组作为参数。

  Bundler.load.dependencies_for(:default,Rails.env).map(&:name).include?(gem_name)

然而,在每个呼叫站点复制组列表似乎不是个好主意。理想情况下,我希望 Bundler 中的方法不需要我指定当前组。 1 bundler网站和手册页主要关注命令行的使用。我还没有找到任何有关宝石公共ruby API的文档。在源代码中的注释是有帮助的,但是关注的是数据类型等。 解决方案 Bundler用于设置应用程序的宝石,所以你可以使用 Gem API而不是 Bundler

  Gem.loaded_specs.has_key? gem_name 

Bundler会设置一些东西,以便捆绑中的任何宝石(在相应的组中)已被激活(所以它们将在 loaded_specs 中有条目),并且任何其他(非捆绑)gem都将被阻止加载。


At runtime, after bundler setup is complete, and groups are applied, what is the best way to programmatically check if a given gem_name is in the bundle?

By reading the source, I've discovered Bundler.definition, e.g.

gem_name = 'banana'
Bundler.definition.dependencies.map(&:name).include?(gem_name)

but unable to find documentation1, I don't know if this is the recommended usage.

Update: It looks like Bundler::Definition#dependencies returns all dependencies, irrespective of groups. As an alternative, I've discovered Bundler::Runtime#dependencies_for which takes groups as arguments.

Bundler.load.dependencies_for(:default, Rails.env).map(&:name).include?(gem_name)

However, it seems like a bad idea to duplicate the "group lists" at every call site. Ideally, I'd like a method in Bundler that doesn't require me to specify the current groups.

1 The bundler website and man page are focused on command-line usage. I have not found any documentation on the gem's public ruby API. Comments in the source are helpful, but focused on data types, etc.

解决方案

Bundler is used to set up the applications gems, so you can use the Gem API rather than Bundler:

Gem.loaded_specs.has_key? gem_name

Bundler will have set things up so that any gems in the bundle (in the appropriate groups) have been activated (so they will have entries in loaded_specs) and any other (non-bundle) gems will be prevented from being loaded.

这篇关于以编程方式检查捆绑中的宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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