7

我想在客户端安装一个 gem (JSON),但前提是尚未安装(一些 1.9 Ruby 发行版捆绑了 JSON)。

我找不到有关如何从gem help install. gem install json在安装了 Ruby 1.9(捆绑了 JSON)的 Windows 系统上运行会导致

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

- 它试图安装它,而忽略了 gem 已经存在的事实。

而且我不能做像 greppinggem list输出这样的 bash 技巧,因为客户端可能是 Windows。

那么只有当系统中不存在gem时才安装gem的多平台方式是什么?

4

4 回答 4

2

This may work...

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

If you don't want to require "json", you can remove it from $LOAD_PATH.

Or, put as a one liner:

ruby -e 'begin; require "some_gem"; rescue LoadError; system "gem install some_gem"; end'
于 2012-04-04T18:31:03.483 回答
2

询问是否安装了 gem:

gem list --installed "^json$"

如果需要,要安装 gem:

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
于 2013-01-24T05:34:19.833 回答
0

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

仅当当前安装的 gem 无法覆盖 gem 规范时,它才会安装。

于 2015-02-20T22:09:05.483 回答
0
gem update json

只应在必要时安装,在我的 Windows 7 系统上安装

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>
于 2012-04-04T12:41:02.427 回答