Reputation: 5148
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
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
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