Read more

Detecting if a Ruby gem is loaded

Henning Koch
September 27, 2016Software engineer at makandra GmbH

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).

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2016-09-27 11:34)