在脚本中安装gem之后,如何加载gem? [英] After installing a gem within a script, how do I load the gem?

查看:138
本文介绍了在脚本中安装gem之后,如何加载gem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小的Ruby脚本来自动化本地机器上的开发环境。因为我不能确定所有机器上都存在 ruby​​zip2 库,所以我会在需要时安装它。

I have a small Ruby script that I'm writing to automate the preparation of a development environment on local machines. Because I can't be certain that the rubyzip2 library is present on all of the machines, I'm having the script install it when needed.

目前,我的脚本正在执行以下操作:

Currently, my script is doing the following:

begin
  require 'zip/zip'
rescue LoadError
  system("gem install rubyzip2")
end

一旦gem安装完成,脚本继续执行;然而,gem并没有被加载,所以所有需要 ruby​​zip2 的代码都暂停执行。

Once the gem has been installed, the script continues execution; however, the gem hasn't been loaded so all code requiring rubyzip2 halts the execution.

如何加载将宝石放入内存中以便脚本可以在安装后继续运行?

How do I load the gem into memory so that the script can continue running after installation?

推荐答案

使用 bundler 版本高于1.10(更新只是运行 gem install bundler ),您可以使用其新的'内联'功能,如 here

With bundler version higher than 1.10 (to update just run gem install bundler) you can use its new 'inline' feature as described here.

require 'bundler/inline'

gemfile(true) do
  source 'https://rubygems.org'
  gem 'catpix'
end

puts Catpix::VERSION

第一个参数 gemfile 方法是应该安装用户系统上尚未安装的gem。

First parameter of gemfile method is whether gems that aren't already installed on the user's system should be installed.

这篇关于在脚本中安装gem之后,如何加载gem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆