Jason Waldrip
Jason Waldrip

Reputation: 5148

Finding the gem root

Is there a way to know the root path of my gem? I am trying to load a default config from a yaml inside the gems path. How do I get the gems root directory with ruby?

Upvotes: 30

Views: 16095

Answers (3)

Matheus Moreira
Matheus Moreira

Reputation: 17020

Given the following project structure:

your_gem/
  lib/
    your_gem.rb

Here's how I would do it:

# your_gem.rb

module YourGem
  def self.root
    File.expand_path '../..', __FILE__
  end
end

Ruby 2.0 introduced the Kernel#__dir__ method; it enables a considerably shorter solution:

# your_gem.rb

module YourGem
  def self.root
    File.dirname __dir__
  end
end

If you need access to the other directories, you can simply build upon root:

module YourGem
  def self.bin
    File.join root, 'bin'
  end

  def self.lib
    File.join root, 'lib'
  end
end

Upvotes: 32

user1182000
user1182000

Reputation: 1635

This is a universal solution for executables and libs. It loads the specification using the Gem API, so the path is always correct:

spec = Gem::Specification.find_by_name("your_gem_name")
gem_root = spec.gem_dir
yaml_obj = YAML.load(gem_root + "/file_name.yaml")

Upvotes: 32

DanS
DanS

Reputation: 18463

gem list <gem> -d

Or if you're using bundler:

bundle show <gem>

Upvotes: 5

Related Questions