问题 如何从ruby脚本引用本地gem?


我需要从普通的ruby脚本引用本地gem,而不需要安装gem。在路上 如何在红宝石中引用本地宝石?,我尝试使用以下设置创建Gemfile:

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

并且脚本如下所示:

require 'custom_gem'
CustomGem::Do.something

当我执行此操作时:

bundle exec ruby script.rb

我明白了:

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

如果我遗漏了 require 'custom_gem' ,我得到:

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

我甚至试过没有捆绑,只是写作 gem ... :path =>̣ ... 在脚本本身,但没有结果。有没有其他方法可以从ruby脚本引用自定义gem,而无需在本地安装gem?


6710
2017-11-25 09:58


起源



答案:


确保您的gem名称与Gemfile中的名称相同(例如 custom_gem

# Gemfile

source "https://rubygems.org"

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

不要忘记使用bundler实际安装此gem

bundle install

之后,脚本应该可以使用了 bundle exec ruby script.rb

# script.rb

require 'custom_gem'
CustomGem::Do.something

12
2017-11-25 10:20



是的,有拼写错误,需要脚本中的宝石以外的东西。谢谢! - tohokami


答案:


确保您的gem名称与Gemfile中的名称相同(例如 custom_gem

# Gemfile

source "https://rubygems.org"

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

不要忘记使用bundler实际安装此gem

bundle install

之后,脚本应该可以使用了 bundle exec ruby script.rb

# script.rb

require 'custom_gem'
CustomGem::Do.something

12
2017-11-25 10:20



是的,有拼写错误,需要脚本中的宝石以外的东西。谢谢! - tohokami