Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recover from failure of require/load in ruby

Tags:

ruby

rake

I recently discovered the Hanna RDoc template and I like it a lot more than the default. I want to use it in my project, but I also don't want my project to require it.

The only change I had to make to my Rakefile to get the hanna template to work was to change

require 'rake/rdoctask'

to

require 'hanna/rdoctask'

Is there any way to attempt a require, and capture/recover from the error? I noticed load and require return a boolean in irb, so I thought maybe I could do this:

unless require 'hanna/rdoctask'
  require 'rake/rdoctask'
end

Sadly, rake aborted as soon as the require failed. Then I tried:

begin
  require 'hanna/rdoctask'
rescue
  require 'rake/rdoctask'
end

but that didn't work either.

Is there any way to accomplish what I'm attempting here?

like image 349
Herms Avatar asked Jan 29 '10 18:01

Herms


2 Answers

Your last option ought to work.

require 'rubygems'
begin
  require 'hanna/rdoctask'
rescue LoadError
  puts 'Hanna rdoc unavailable, falling back to rake'
  require 'rake/rdoctask'
end

works on my machine, running Ruby 1.8.7p248 with the "rake" gem installed, but not the "hanna" gem. Are you certain you have rubygems required in your environment, though? If not, requiring 'rake/rdoctask' might also fail.

like image 199
Greg Campbell Avatar answered Sep 23 '22 04:09

Greg Campbell


I noticed load and require return a boolean in irb

The return value of require tells you whether the library was actually loaded: it's true if the library was loaded and false if the library was found but not loaded because it had already been loaded.

Failure is indicated with a LoadError exception.

like image 31
Jörg W Mittag Avatar answered Sep 22 '22 04:09

Jörg W Mittag