Mourad
Mourad

Reputation: 474

How to require a Ruby gem directly from its path?

In order to work with rubyzip i installed the gems:

gem install --local rubyzip-1.1.7.gem  
gem install --local zip-zip-0.3.gem

In my code i call the gems using the require method:

  require 'zip/zip' 
  require 'zip/filesystem'

I want to use require to load the gems directly from their location on my machine.

i want somthing like this:

 require 'path_to_my_zip_gem'

Where path_to_my zip_gem contains the gem files

Upvotes: 2

Views: 3279

Answers (2)

Max
Max

Reputation: 2230

The simpliest answer is

Gem::Specification.find_by_name("GEM_NAME_HERE").full_gem_path

Example

> require File.join(Gem::Specification.find_by_name("railties").full_gem_path, "lib/rails/code_statistics.rb")
=> true

Upvotes: 1

smileart
smileart

Reputation: 1596

Basically, it's because require method loads files by name from paths listed in $: or $LOAD_PATH

"If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $LOAD_PATH ($:)."

http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-require

If you want to require a gem from the "local" path then the require_relative method could help since you can specify a path relative to the requiring file’s path. Look at the official documentation for further details:

http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-require_relative

Upvotes: 1

Related Questions