开发者

Recover from failure of require/load in ruby

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/rdocta开发者_如何学运维sk'

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜