Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the gem root

Tags:

ruby

gem

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?

like image 721
Jason Waldrip Avatar asked Apr 12 '12 22:04

Jason Waldrip


People also ask

Where is the gem file located?

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.

Where are gems installed on Mac?

By default, binaries installed by gem will be placed into: /usr/local/lib/ruby/gems/3.1.

What is RubyGems How does it work?

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.

Where can I find RubyGems?

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.


2 Answers

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 
like image 196
Matheus Moreira Avatar answered Oct 08 '22 07:10

Matheus Moreira


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") 
like image 26
user1182000 Avatar answered Oct 08 '22 06:10

user1182000