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?
The Gemfile is wherever you want it to be - usually in the main directory of your project and the name of the file is Gemfile . It's convenient to have one because it allows you to use Bundler to manage which gems and which versions of each your project needs to run.
By default, binaries installed by gem will be placed into: /usr/local/lib/ruby/gems/3.1.
The RubyGems software allows you to easily download, install, and use ruby software packages on your system. The software package is called a “gem” which contains a packaged Ruby application or library. Gems can be used to extend or modify functionality in Ruby applications.
The main place where libraries are hosted is RubyGems.org, a public repository of gems that can be searched and installed onto your machine. You may browse and search for gems using the RubyGems website, or use the gem command. Using gem search -r , you can search RubyGems' repository.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With