Detecting if a Ruby gem is loaded

Updated . Posted . Visible to the public.

Detect if a gem has been activated

A gem is activated if it is either in the current bundle (Gemfile.lock), or if you have manually activated it using Kernel#gem Show archive.org snapshot (old-school).

To detect if e.g. activerecord has been activated:

if Gem.loaded_specs.has_key?('activerecord')
  # ActiveRecord was activated
end

Detect if a particular gem version has been activated

To detect if e.g. activerecord matches a requirement like >= 3.2.0:

requirement = Gem::Requirement.new('>= 3.2.0')
version = Gem.loaded_specs['activerecord'].version
if requirement.satisfied_by?(version)
  # ActiveRecord 3.2+ was activated
end  

Detect if a gem has been required

Rails will automatically require all the gems in your Gemfile, unless you pass the require: false option. When working on non-Rails project (such as a gem), nothing is required automatically.

To detect if a gem has been required, use defined? on one of the modules defined by that gem:

if defined?(ActiveRecord)
  puts 'ActiveRecord has already been required'
end  

Note that defined? is a keyword (not a method) and will not crash while evaluating its argument.

Henning Koch
Last edit
Henning Koch
Keywords
ruby, bundler
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-09-27 09:34)