Read more

A Ruby script that installs all gems it is missing

Dominik Schöler
May 21, 2014Software engineer at makandra GmbH

So you want your Ruby script to install missing gems instead of dying? Take this method:

def installing_missing_gems(&block)
  yield
rescue LoadError => e
  gem_name = e.message.split('--').last.strip
  install_command = 'gem install ' + gem_name
  
  # install missing gem
  puts 'Probably missing gem: ' + gem_name
  print 'Auto-install it? [yN] '
  gets.strip =~ /y/i or exit(1)
  system(install_command) or exit(1)
  
  # retry
  Gem.clear_paths
  puts 'Trying again ...'
  require gem_name
  retry
end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Use it like this:

installing_missing_gems do
  require 'thor'
  require 'nokogiri'
  # some code using those gems
end
Posted by Dominik Schöler to makandra dev (2014-05-21 16:18)