Question

Is there any way to do something like this pseudo-code?

puts was_required?('my-library')
=> false

require('my-library')
puts was_required?('my-library')
=> true

I want to be able to test if I have required some library, whether is a Gem o or a Rake task, by it's require-name.

I could test a gem testing if the Class the gem loads is available, but I would really love to test using the library name, no the class name.

For rake tasks is the same. I can find in Rake.tasks if there is a task from the library I have required, by I would like to test with the library name, no for tasks names

thanks

Was it helpful?

Solution

Perhaps you want to play around with $LOADED_FEATURES (alias of $"), that array that contains the module names loaded by require?

def was_required?(file)
  rex = Regexp.new("/#{Regexp.quote(file)}\.(so|o|sl|rb)?")
  $LOADED_FEATURES.find { |f| f =~ rex }
end

was_required?('uri')
#=> false
require 'uri'
#=> true
was_required?('uri')
#=> true

Btw this is exactly what Ruby does in the require method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top