2012-04-04 121 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

它將安裝只有寶石規格無法通過當前已安裝的寶石覆蓋。