使用捆绑器,判断 gem 是否为 "requirable" 的最佳方法是什么?

With bundler, what's the best way to tell if a gem is "requirable"?

在我的 Gemfile 中说我有

group :test do
  gem 'rspec-core', require: false
end

有没有简单的方法可以查看test群是否被捆绑? (例如,在这种情况下 bundle 可能在有或没有 --without test 的情况下被调用)。

我找不到,所以我开始寻找是否需要 rspec-core,并找到了一些明显的解决方案:

 Bundler.definition.index.search("rspec-core")
 # or
 Gem.loaded_specs["rspec-core"]

什么是最稳定的API来判断gem是否需要?

(没有试图要求它并拯救 LoadError

当生成 Rails 应用程序时,它通常包含一行使用 Rails.env 来确定需要哪个组。它应该看起来像这样 Bundler.require(:default, Rails.env)。这通常发生在 Rails 应用程序的初始化过程中。这是执行此操作的一些代码片段:

class Rails::Boot
  def run
    load_initializer

    Rails::Initializer.class_eval do
      def load_gems
        @bundler_loaded ||= Bundler.require :default, Rails.env
      end
    end

    Rails::Initializer.run(:set_load_path)
  end
end

因此,如果您 Rails.env 正在测试,它将需要测试组中的所有宝石。

我要继续说 Gem.loaded_specs 比通过捆绑器更可靠;我发现了 bundler 1.12.5 的一个情况,在我传递给 without 的其中一个组中,我有一个来自 GitHub 的 gem,这导致 Bundler.definition.index.search 引发 Bundler::PathError 引用 GitHub 中的 gem 我故意不捆绑。