Rubygems: Install if not already installed

  • Thread starter Bret Pettichord
  • Start date
B

Bret Pettichord

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top