Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Wednesday, June 10, 2009

RubyGems Best Practice

It is unexpectedly difficult To handle RubyGems with multi ruby implementation in one OS. This entry is drawing my best practice of the problem.

Principle: Gem in the User Area

As far as possible, we should install gem libraries in a user area instead of the root area.

You shouldn't run such a command

$ sudo gem install {something}


$ gem install {something}

By this way the new library will be installed under ~/.gem/ruby/1.8 if your ruby is ruby1.8.*.

Note that we have to write it on your ~/.zshrc.

export PATH=~/.gem/ruby/1.8/bin:$PATH

Now let's uninstall all your gem libraries on the root area!

$ yes | sudo gem uninstall '' -a

Multi Ruby Implementation

Assume that you have more than four ruby implementations on your OS.

So how to distinguish them?

  • ruby1.8.6: Just Ignore

  • ruby1.8.7: Default

  • ruby1.9.1: Suffix '191' for any commands

  • ruby1.9.2: Suffix '192' for any commands

It is easy to ignore ruby1.8.6 by export PATH=/opt/local/bin:$PATH on your ~/.zshrc.

How can I install a gem library into the specific version of the ruby?

  • ruby1.8.7: gem install {name}

  • ruby1.9.1: gem191 install {name} --format-executable

  • ruby1.9.2: gem192 install {name} --format-executable

Note that there's no 'sudo's.

Where will those commands deploy it?

  • ruby1.8.7: under ~/.gem/ruby/1.8

  • ruby1.9.1: under ~/rubies/lib/ruby/gems/1.9.1

  • ruby1.9.2: under ~/rubies/lib/ruby/gems/1.9.1

The list may surprise you. Yes, it's not typo.

  • When 1.8.7's gem command is called by normal user, first it tries to install under /opt/local/lib/ruby/gems/1.8 and fails, then tries to install under ~/.gem/ruby/1.8 and succeeds. The minor version is ignored automatically.

  • When 1.9.1's gem command is called by normal user, first it tries to install under ~/rubies/lib/ruby/gems/1.9.1 and succeeds (the configure option --prefix=~/rubies matters)

  • 1.9.2 is considered as 1.9.1! Look at it

    $ ruby192 -rrbconfig -e 'p RbConfig::CONFIG["ruby_version"]' "1.9.1"

Therefore, just write it on your ~/.zshrc

export PATH=~/.gem/ruby/1.8/bin:$PATH
export PATH=~/rubies/lib/ruby/gems/1.9.1/bin:$PATH


It is laborious to type --format-executable everytime. This is where .gemrc comes in. Add this line: 'gem: --no-ri --format-executable'. This also works for ruby1.8.7, but you don't have to care about it because there's no bad side effect.

You may mistype 'sudo gem install ...' someday. In terms of human computer interface, it is better not to do a wrong way by computer supports than by human efforts. Let's prohibit root to do gem! Write below on your ~/.zshrc.

function sudo() {
  if [ $1 = "gem" ]; then
    echo "Use gem without sudo!"
    command sudo $*


No comments:

Post a Comment