Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically check if gem in bundle?

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.

like image 828
Jared Beck Avatar asked Dec 16 '14 17:12

Jared Beck


1 Answers

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.

like image 110
matt Avatar answered Oct 27 '22 15:10

matt