Safely require gems in Ruby

2019-07-03 19:09发布

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
else
  # do other stuff
end

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

2条回答
贪生不怕死
2楼-- · 2019-07-03 19:28

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

查看更多
3楼-- · 2019-07-03 19:41

It would probably be done like this:

begin
  require 'hirb'
rescue LoadError => e
  puts "could not find hirb"
end
查看更多
登录 后发表回答