How to find the path a Ruby Gem is installed at (i.e. Gem.lib_path c.f. Gem.bin_path)

29,922

Solution 1

The problem with the checked answer is that you must "require" the rubygem or it won't work. Often this is undesireable because if you're working with an executable gem, you don't want to "require" it or you'll get a bunch of warnings.

This is a universal solution for executables and libs:

spec = Gem::Specification.find_by_name("cucumber")
gem_root = spec.gem_dir
gem_lib = gem_root + "/lib"

If you want to get really technical, there isn't just one lib directory. The gemspec has a "require_paths" array of all the directorys to search (added to $LOAD_PATH). So, if you want an array of the require_paths, use this:

gem_lib = gem_root + "/" + spec.require_paths[0]

No need for bundler.

Solution 2

After the gem has been loaded with require, you find the lib path using Gem.loaded_specs as follows:

require 'rubygems'
require 'cucumber'
gem_root = Gem.loaded_specs['cucumber'].full_gem_path
gem_lib = File.join(gem_root, 'lib')

Solution 3

I'm not sure why you're doing this, but if you're on the command line, use gem env.

Solution 4

Try using bundle show cucumber.

Which, from looking at the source of bundler does something like:

spec = Bundler.load.specs.find{|s| s.name == name }
spec.full_gem_path

You are using bundler, right?

Share:
29,922

Related videos on Youtube

Hedgehog
Author by

Hedgehog

Updated on April 10, 2020

Comments

  • Hedgehog
    Hedgehog about 4 years
    Gem.bin_path('cucumber', 'cucumber')
    

    Will return the binary/executable's path. It seems there is no such function to return the library path. Which in this case would, ideally, return:

    /home/hedge/.rvm/gems/ruby-1.9.2-p136@bbb-bdd-meta-bdd/gems/cucumber-0.10.0/lib
    

    Have I missed something or is there a simple/one method way to get this information?

    Updated: No CLI or non-stdlib suggestions please.

  • Hedgehog
    Hedgehog about 13 years
    Big no to Bundler, I've patched it extensively, so know what goes on when you start using it in tour code. Nonetheless, alone the git issues listed make it off limits - but interesting to keep an eye on :)
  • Hedgehog
    Hedgehog about 13 years
    Sorry, should have been explicit - no cli, just api.
  • David K
    David K almost 12 years
    This works perfectly for rubygems 1.3.6 for example, (version that comes on the mac as standard), whereas the Gem::Specification.find_by_name("cucumber") wont. Cheers Guy, saved me a bunch of trouble!
  • Joshua Pinter
    Joshua Pinter over 10 years
    Thanks for the simplicity, exactly what I was looking for.