Take the 2-minute tour ×

Is there a way to require a ruby gem safely so as to not raise an exception if the gem is not found?

I am looking a solution close to this:

if require 'hirb'
  # do some hirb related stuff
  # do other stuff

I want this to make sure no unnecessary gems are failing my deploys to production.

share|improve this question
Ruby should have a kind_of_want command for when you don't really require something. –  Andrew Grimm Sep 6 '11 at 0:00
def would_like(gemname, &block); begin; require gemname; yield; rescue LoadError; puts "Could not load #{gemname}"; end; end :D –  vrinek Sep 6 '11 at 7:18
add comment

2 Answers

up vote 8 down vote accepted

It would probably be done like this:

  require 'hirb'
rescue LoadError => e
  puts "could not find hirb"
share|improve this answer
add comment

The best way to do this is to use bundler, that way you can be sure your gems really will be installed.

share|improve this answer
Bundler is good for what it does but it doesn't help my situation for where I want to do this check. –  vrinek Sep 5 '11 at 12:23
Ok, i'd use Kernel.gem then to load a gem, and make sure it's a gem and not some other file. –  sunkencity Sep 5 '11 at 12:25
add comment

Your Answer


