2012-04-04 113 views
7

我想在客户端安装一个gem(JSON),但只有在尚未安装的情况下(大约1.9个Ruby发行版才会捆绑JSON)。按需安装gem

我无法找到如何做到这一点从gem help install线索。而Windows系统使用Ruby 1.9安装(与JSON捆绑)的结果上运行gem install json

ERROR: Error installing json: 
    The 'json' native gem requires installed build tools. 

- 它试图安装它忽略一个事实,即创业板已经存在。

我不能做的bash的技巧,比如grepping gem list输出,因为客户可能是Windows操作系统。

那么什么是安装宝石只有当它不存在于系统中已有的多呢?

回答

2

这可能工作装,在我的Windows 7系统...

begin 
    require "json" 
rescue LoadError 
    system("gem install json") 
end 

如果您不希望要求“JSON “,你可以从$ LOAD_PATH中删除它。

或者,把作为一个班轮:

ruby -e 'begin; require "some_gem"; rescue LoadError; system "gem install some_gem"; end' 
+0

太好了,明天会测试它并接受你的答案,因为它似乎是工作解决方案。唯一的问题是'json'实际上可以由两个gems提供 - json_pure和json,所以根据你需要的变体,你需要'require'json/ext''或'require'json/pure''。 – 2012-04-04 19:16:44

+0

是的。实际上我认为这不是最好的方法,因为我们必须手动从$ LOAD_PATH中删除路径。如果json/ext或json/pure没有被包含,那会更好。 – Tomato 2012-04-04 23:09:39

+0

我正在执行命令行中的单行命令,所以我不需要删除任何内容,所以这就是我真正需要的感谢! – 2012-04-05 08:37:40

0
gem update json 

只应在必要时它

C:\Ruby193\bin>gem update json 
Updating installed gems 
Updating json 
Fetching: json-1.6.6.gem (100%) 
Temporarily enhancing PATH to include DevKit... 
Building native extensions. This could take a while... 
Successfully installed json-1.6.6 
Updating multi_json 
Fetching: multi_json-1.2.0.gem (100%) 
Successfully installed multi_json-1.2.0 
Gems updated: json, multi_json 
Installing ri documentation for json-1.6.6... 
Installing ri documentation for multi_json-1.2.0... 
Installing RDoc documentation for json-1.6.6... 
Installing RDoc documentation for multi_json-1.2.0... 

C:\Ruby193\bin>gem update json 
Updating installed gems 
Nothing to update 

C:\Ruby193\bin> 
+1

如果您尝试执行'gem update'是未安装的宝石 - 它会失败 – 2012-04-04 13:05:26

+0

上面的截图证明我是正确的,我没有第一次安装宝石,它安装了,第二次没有 – peter 2012-04-05 11:05:36

2

要问,如果安装了宝石:

gem list --installed "^json$" 

要,如果它需要安装一个宝石:

ruby -e '`gem list -i \"^json$\"`.chomp=="true" or `gem install json`' 

要做一个命令行脚本:

#!/usr/bin/env ruby 
# 
# Ruby script to install a gem if it's needed. 
# This script first uses gem list to see if the 
# gem is already installed, matching the exact name. 
# 
# If the gem is installed, then exit. 
# If the gem is not installed, then install it. 
# 
# You can this script whatever you like; 
# I call mine gem-install-fast because it's 
# faster than re-installing a gem each time. 
# 
# Example: 
# 
# gem-install-fast json 
# 
name=ARGV[0] and `gem list -i "^#{name}$"`.chomp=="true" or `gem install #{name}` 

要使用命令行脚本:

gem-install-fast json 
0

我找到的最好的是这个(shell命令): $ gem install asciidoctor --conservative

它将安装只有宝石规格无法通过当前已安装的宝石覆盖。