Finding the gem root
ruby, rubygems
Solution
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
Problem
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?