Checking if a required gem is installed from within code
suggest changeTo check if a required gem is installed, from within your code, you can use the following (using nokogiri as an example):
begin
found_gem = Gem::Specification.find_by_name('nokogiri')
require 'nokogiri'
# The rest of your code goes here.
rescue Gem::LoadError
end
This can be wrapped in a method used while setting up the rest of the program.
def gem_installed?(gem_name)
found_gem = false
begin
found_gem = Gem::Specification.find_by_name(gem_name)
rescue Gem::LoadError
return false
else
return true
end
end
Now you can check if the required gem is installed, and print an error message.
if gem_installed?('nokogiri')
require 'nokogiri'
else
printf "nokogiri gem required\n"
exit 1
end
or
if gem_installed?('nokogiri')
require 'nokogiri'
else
require 'REXML'
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents