简体   繁体   中英

How to reference a local gem from a ruby script?

I need to reference a local gem from a plain ruby script, without installing the gem. On the trail of How to refer a local gem in ruby? , i tried creating a Gemfile with the following setup:

%w(
  custom_gem
  another_custom_gem
).each do |dependency|
  gem dependency, :path => File.expand_path("../../#{dependency}", __FILE__)
end

and the script looks like this:

require 'custom_gem'
CustomGem::Do.something

When I execute this with:

bundle exec ruby script.rb

I get:

script.rb:1:in `require': cannot load such file -- custom_gem (LoadError) from script.rb:1:in `<main>'

If I leave out the require 'custom_gem' , I get:

script.rb:3:in `<main>': uninitialized constant CustomGem (NameError)

I even tried without bundler, and just writing gem ... :path =>̣ ... in the script itself, but without results. Is there any other way of referencing custom gems from ruby scripts, without installing the gems locally?

Make sure that your gem name as same as in Gemfile (eg custom_gem )

# Gemfile

source "https://rubygems.org"

gem "custom_gem", path: "/home/username/path/to/custom_gem"

Don't forget to actually install this gem using bundler

bundle install

After that, the script should be ready to use by bundle exec ruby script.rb

# script.rb

require 'custom_gem'
CustomGem::Do.something

在不使用Gemfile的情况下,您可以通过在gem的根目录中运行bundle exec rake install来安装本地版本的gem,然后您可以像任何其他已安装的gem一样引用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM