以编程方式检查捆绑中的宝石? [英] Programmatically check if gem in bundle?
问题描述
在运行时,捆绑器安装完成并应用组后,什么是以编程方式检查给定 gem_name
是否在捆绑包中的最佳方式?
Bundler.definition $ c
$ 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屋!