[Rubygems-developers] Gem methods?

Jeremy Hinegardner jeremy at hinegardner.org
Thu Oct 9 13:18:19 EDT 2008

On Thu, Oct 09, 2008 at 08:29:15AM -0700, Trans wrote:
> Is there a way to see if a gem is active (without activating it of
> course)?

Looking at the rubygems code for Gem.activate I'm assuming that an 'active' gem
means that the spec.require_paths have been added to $LOAD_PATH.  Without
examining $LOAD_PATH there is an @loaded_specs member variable of the Gem module
you could acces, but it is not publicly available.  

Using the API, take a bit of the code from Gem.activate and use it.

    require 'rubygems'

    def is_active?( name, version_req = ::Gem::Requirement.default )
      dep = ::Gem::Dependency.new( name, version_req )
      idx = Gem::SourceIndex.from_gems_in( *Gem::SourceIndex.installed_spec_directories )
      matches = idx.find_name( dep.name, dep.version_requirements )

      matches.each do |spec|
        spec.require_paths.each do |req_path|
          req_path = File.join( spec.full_gem_path, req_path )
          if $LOAD_PATH.include?( req_path ) then
            return req_path
      return false

    puts "Is the configuration gem loaded ? : #{is_active?( 'configuration' )}" # => false
    require 'configuration'
    puts "Is the configuration gem loaded ? : #{is_active?( 'configuration' )}" # => /opt/local/lib/ruby/gems/1.8/gems/configuration-0.0.5/lib

> In addition is there a way to access a gemspec from code?

See the first 3 lines of the is_active? method above for a way to search for a gemspec.
> Lastly, is there a way to get the path to where a gem is installed?

Given that you found the spec above, you can do 'spec.full_gem_path'

Or if you want all of them:

  Gem.source_index.each do |full_name, spec|
    puts "#{full_name} is installed in #{spec.full_gem_path}"

> Thanks,
> T



 Jeremy Hinegardner                              jeremy at hinegardner.org 

More information about the Rubygems-developers mailing list