ZSH Completion for gem and gem open

I've been trying to get my head around the ZSH completion system. It's not easy, but I'm slowly making progress.

Here's my first semi-successful attempt. It provides command completion for gem (including installed commands) and gem name completion for specific gem commands (update, and open from Adam Sanderson).

So typing gem <tab> gives a list of possible commands, whilst gem open <tab> will complete with the names of the currently installed gems.

#compdef gem

_gem_commands () {
  if [[ -z $gem_commands ]] ; then
    gem_commands=$(gem help commands | grep '^    [a-z]' | cut -d " " -f 5)
  fi
  
  # This seems unnecessary, but if I try to set gem_commands to an array, it falls over.
 
  typeset -a gem_command_array
  gem_command_array=($(echo $gem_commands))
  compadd $gem_command_array
}
 
_installed_gems () {
  if [[ -z $installed_gems ]] ; then
    installed_gems=($(gem list | grep '^[A-Za-z]' | cut -d " " -f 1))
  fi
  
  typeset -a installed_gem_array
  installed_gem_array=($(echo $installed_gems))
  compadd $installed_gem_array
}
 
if (( CURRENT == 2 )); then
  _gem_commands
else
  if [[ $words[2] == open || $words[2] == update ]] ; then
    _installed_gems
  fi
fi

As it's a first attempt, it's a long way from perfect. I've put it on gist, for other people to play with, and I'd appreciate any advice or improvements. Specifically I'd like to know how to avoid the use of both gem_command_array and gem_commands. I'd also like to know a better way to check if the given command is in the list [open, update].

Please fork the gist, or tweet me with your suggestions.

Adam Sanderson's open_gem

The latest version of rubygems (1.3.2) now has an interface to add commands. Making great use of this feature, Adam Sanderson has written open_gem, a simple but amazingly useful tool.

You use it like this:

$ gem open activerecord

This opens the activerecord gem in your favourite editor (taken from either $GEM_OPEN_EDITOR or $EDITOR environment variables). If there are multiple versions of the gem installed, it will show a menu, letting you choose which version you require.

$ gem open activerecord
Open which gem?
 1. activerecord 2.1.0
 2. activerecord 2.3.2
> 

open_gem itself is a gem, and can be installed with:

$ gem install open_gem

To get it working, you need to have $EDITOR set to something sensible:

$ export EDITOR=mate

If you're running on OS X and use TextMate, you may have already set $EDITOR to mate -w, which let's you use TextMate as the editor for git commit messages and much more. However, the -w flag doesn't work with open_gem, so set the $GEM_OPEN_EDITOR variable, and open_gem will use that instead:

$ export GEM_OPEN_EDITOR=mate

You should now be good to go. If you want to see how it works, just use it on itself!

$ gem open open_gem