How to require a Ruby gem directly from its path?

折月煮酒 提交于 2019-12-11 01:37:38

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/30187990/how-to-require-a-ruby-gem-directly-from-its-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!