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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)