Recover a Load Error
Installing a gem from a load error
Although recovering a LoadError
is not a preferred approach in Ruby development, sometimes its needed when you are building one-off command line scripts. It simplifies the installation of gems as the user is running the script.
Below is the approach, to run the GemRunner
directly:
begin
require 'sass'
rescue LoadError
require 'rubygems/gem_runner'
gemrunner = Gem::GemRunner.new
gemrunner.run(['install', 'nokogiri','--bindir',"#{File.expand_path File.dirname(__FILE__)}/bins"])
require 'sass'
end
Again, typically you would want to define all your libraries in a Gemfile
and use bundle
.