Last Updated: February 25, 2016
·
491
· knowshan

Requiring ruby gems and failing with a user friendly exception

Ruby's begin-rescue blocks can be used to require gem(s) and failing with a user friendly exception in case it's absent.

Tested with: Ruby 1.8.7 and 1.9.2

#!/usr/bin/env ruby

require 'rubygems'
# Load dependency Ruby gems
gem_req = {'libvirt' => 'creating VM     domain','nokogiri' => 'XML formatting'}
gem_req.each do |g,u|
  begin
    require g
  rescue Exception => e
    puts "This script requires #{g} gem."
    puts "The #{g} gem is used for #{u}"
    puts "Install all gems listed in the Gemfile"
    exit 1
  end
end

It's helpful to tell users why a particular gem is required in the script.