Neil
Neil

Reputation: 625

How do you check if a library/ruby-gem has been loaded?

In ruby code, how would I check what external libraries are loaded? For example,

require 'some-library'
if is-loaded?('some-library')
  puts "this will run"
end

or

# require 'some-library' Don't load it in here
if is-loaded?('some-library')
  puts "this will not run"
end

Is there a way to do this?

Note on why I need this: I'm working on boom, and on windows, it will try to include 'Win32/Console/ANSI', to enable ANSI color codes like \e[36m. What I'm trying to do is if the system is windows and 'Win32/Console/ANSI' is not loaded, it would append the color codes, so the color codes are not outputted. Here is the file.

Upvotes: 29

Views: 17854

Answers (5)

barbacan
barbacan

Reputation: 632

try this :

def loaded?(name)
  r = Regexp.new("#{name}.rb$")
  $LOADED_FEATURES.select{|t| t.match(r) }.any?
end

Be sure of the name of your module (search here $LOADED_FEATURES).

Upvotes: 5

Joshua Pinter
Joshua Pinter

Reputation: 47471

Require Library Unless Already Loaded

For simplicity, here's how you load a library unless it's already loaded:

require 'RMagick' unless defined?(Magick)

Upvotes: 7

Carl Zulauf
Carl Zulauf

Reputation: 39558

If you want to safely try requiring a gem/library that may or may not be available, use something like this:

begin
  require 'securerandom'
rescue LoadError
  # We just won't get securerandom
end

This works even if the gem in question has already been required. In that scenario the require statement will do nothing and the rescue block will never execute.

If you are just interested in whether or not a gem/library has already been loaded, check to see if one of its constants is present. I do something like this to dynamically load additional functionality if ActiveSupport is loaded:

if defined?(ActiveSupport)
  require "active_support/cache/redis_store"
end

You can also use the opposite to load a compatibility layer if the gem/library is NOT present. For example, I use some Hash methods that don't exist in Ruby's core Hash implementation, but are added by ActiveSupport. So, I define those methods when my gem runs in an environment where ActiveSupport doesn't exist.

require 'core_ext/hash' unless defined?(ActiveSupport)

Upvotes: 8

yfeldblum
yfeldblum

Reputation: 65435

Most libraries will typically define a top-level constant. The usual thing to do is to check whether that constant is defined.

> defined?(CSV)
#=> nil

> require "csv"
#=> true

> defined?(CSV)
#=> "constant"

> puts "loaded!" if defined?(CSV)
loaded!
#=> nil

Upvotes: 31

declan
declan

Reputation: 5625

require will throw a LoadError if it can't find the library you are trying to load. So you can check it like this

begin
  require 'some-library'
  puts 'This will run.'
rescue LoadError
  puts 'This will not run'
  # error handling code here
end

Upvotes: 12

Related Questions