Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I load a gem from source?

Tags:

ruby

rubygems

gem

I have git cloned a repo from Github, now I want to experiment with it, as in I want to poke around the code and mess with it. I've created a file test.rb that should load this gem, but I want to load my locally checked out version, what's the right way to do this?

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

like image 661
foobar Avatar asked Sep 08 '12 20:09

foobar


2 Answers

Following apneadiving's suggestion 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.

like image 116
foobar Avatar answered Oct 01 '22 15:10

foobar


When you require 'foo' Ruby checks all the directories in the load path for a file foo.rb and loads the first one it finds. If no file named foo.rb is found, and you’re not using Rubygems, a LoadError is raised.

If you are using Rubygems (which is likely given that it is included in Ruby 1.9+), then instead of immediately raising a LoadError all the installed Gems are searched to see if one contains a file foo.rb. If such a Gem is found, then it is added to the load path and the file is loaded.

You can manipulate the load path yourself if you want to ensure a particular version of a library is used. Normally this isn’t something that’s recommended, but this is the kind of situation that you’d want to do it.

There are two ways of adding directories to the load path. First you can do it in the actual code, using the $LOAD_PATH (or $:) global variable:

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

Note that you normally want to add the lib dir of the gem, not the top level dir of the gem (actually this can vary depending on the actual Gem, and it’s possible to need to add more than one dir, but lib is the norm).

The other way is to use the -I command line switch to the ruby executable:

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

This way might be a bit cleaner, as normally you don’t want to be messing with the load path from inside your code, but if you’re just testing the library it probably doesn’t matter much.

like image 45
matt Avatar answered Oct 01 '22 14:10

matt