Programmatically check if gem in bundle?

人走茶凉 提交于 2019-12-23 08:53:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27510136/programmatically-check-if-gem-in-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!