按需安装gem

时间:2012-04-04 09:29:22

标签: ruby rubygems gem

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

我无法从gem help install找到关于如何做到这一点的线索。在安装了Ruby 1.9(捆绑了JSON)的Windows系统上运行gem install json会导致

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

- 它试图安装它忽略宝石已经存在的事实。

我不能像grepping gem list输出那样做bash技巧,因为客户端可能是Windows。

那么只有在系统中不存在宝石的情况下才能安装宝石的多平台方式是什么?

4 个答案:

答案 0 :(得分:2)

这可能有用......

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'

答案 1 :(得分:2)

询问是否安装了宝石:

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

答案 2 :(得分: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>

答案 3 :(得分:0)

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

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