tags:

views:

56

answers:

2

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?

A: 

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.

Greg Campbell
require 'rubygems' is in the rakefile, but that shouldn't matter as I have the rubygems value set in RUBYOPT.
Herms
That worked. Not sure why my initial attempt was failing.
Herms
Because you didn't rescue `LoadError`, you rescued `StandardError` which is the default if no exception is specified.
Jörg W Mittag
+1  A: 

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.

Jörg W Mittag