Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say in my Gemfile I have

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

Is there an easy way to see if the test group has been bundled? (like, in this case bundle may have been called with or without --without test).

I couldn't find one, therefore I started looking for whether or not rspec-core is requirable, and found a few apparent solutions:

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

What's the most stable API to determine if the gem is requirable?

(without trying to require it and rescuing LoadError)

like image 277
Gabe Kopley Avatar asked Aug 21 '16 17:08

Gabe Kopley


1 Answers

When a Rails app is generated it typically includes a line that uses Rails.env to determine which group to require. It should look something like this Bundler.require(:default, Rails.env). This typically happens in the initialization of a Rails App. Here is a snippet of some code that does that:

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

So if you Rails.env is test it will require all the gems in the test group.

like image 189
user2977636 Avatar answered Nov 18 '22 06:11

user2977636