How to load a gem from a source?

I have git cloned a repo from Github, now I want to experiment with it, since I want to pop the code and mess with it. I created a test.rb file that should download this pearl, but I want to download my locally verified version, what's the right way to do this?

Right now I just use a bunch of "require_relative 'the_gem_name/lib/file'" which feels wrong.

+6
source share
2 answers

When require 'foo' Ruby checks all the directories in the download path of the foo.rb file and loads the first one found. If a file named foo.rb not found and you are not using Rubygems, a LoadError is created.

If you use Rubygems (which most likely indicates that it is included in Ruby 1.9+), instead of raising a LoadError right LoadError , all the Gems found look for if there is a foo.rb file. If such a Gem is found, then it is added to the download path and the file is downloaded.

You can manipulate the download yourself if you want a specific version of the library to be used. This is usually not recommended, but this is the situation you would like to do.

There are two ways to add directories to the boot path. First you can do this in real code using the global variable $LOAD_PATH (or $: :

 $LOAD_PATH.unshift '/path/to/the/gems/lib/' require 'the_gem' 

Note that you usually want to add the lib dir label for the gem, and not for the top level gem (in fact, this may vary depending on the actual Gem, and it is possible to add more than one directory, but lib is the norm).

Another way is to use the -I command line -I in the ruby executable:

 $ ruby -I/path/to/the/gems/lib/ test.rb 

This method might be a little cleaner since you usually donโ€™t want to bother with the download course from inside your code, but if you are just checking the library, it probably doesn't matter much.

+8
source

Following the hint in the comments, I created a Gemfile and added this line

 source "http://rubygems.org" gem 'gem_name', path: '~/path/to/gem/source/folder' 

Then bundle install and bundle exec ruby test.rb and it worked.

+3
source

Source: https://habr.com/ru/post/924926/


All Articles