Rubygems: Install if not already installed


#1

One of the things that I’ve needed to do on several occasions is
create scripts that will update an Ruby installation to include all
the gems that a project requires. I first wrote a batch file with
several calls to “gem install”. It worked, but it was somewhat slow,
because it would reinstall all the gems. I really only wanted it to
install a specified gem if it weren’t installed.

I finally went ahead, however, and wrote the code to only install the
gems if necessary. Here it is.

module Gem

Return a list of the versions of the specified gem that are

installed.
def self.installed_versions gem_name
cache.search(gem_name).collect {|x| x.version.to_s}
end

Return the version of the provided gem file name.

@@gem_file_regex = /^(.)-([^-]).gem$/
def self.file_version gem_file
if @@gem_file_regex =~ gem_file
$2
else
nil
end
end

Return the library name of the gem file.

def self.file_gem_name gem_file
if @@gem_file_regex =~ gem_file
$1
else
nil
end
end
end

gem_dir = File.dirname(FILE) + ‘/gems’

desc “Install any gems from the local gems directory that are not
already installed.”
task ‘update-gems’ do
Dir.chdir gem_dir do
Dir[’*.gem’].each do | gem_file |
version = Gem::file_version gem_file
name = Gem::file_gem_name gem_file
desc = “Gem #{name}, version #{version}”
if Gem::installed_versions(name).include? version
puts “#{desc} already installed.”
else
if system “gem.bat install --local #{name}”
puts “#{desc} installed.”
else
raise RuntimeError, “Unable to load #{desc}”
end
end
end
end
end