The Twilight Sun

Archive for May, 2011

Using retry after a LoadError

by Jonathan on May.12, 2011, under Ruby

Someone in the Ruby IRC channel pastied this code today and complained about how ugly it is:

begin
  require 'vlad'
rescue LoadError
  require 'rubygems'
  begin
    require 'vlad'
  rescue LoadError
  end
end

It’s meant to account for differences between Ruby 1.8 and 1.9, where rubygems is automatically loaded. And this code is pretty ugly. I came up with a simplified version that takes advantage of require()’s return value, and the `retry` statement:

begin
  require 'vlad'
rescue LoadError
  retry if require('rubygems')
  # raise
end

The `retry` keyword jumps back to the start of the ‘begin’ block so you can try to load your libraries again. Used carelessly this would turn into an infinite loop (LoadError occurs, retry, LoadError occurs, retry, ad nauseum), but since require() returns false if the library was already loaded, you can skip the retry in that case.

This version eats the LoadError, which is useful for an optional dependency, but if you don’t want that you can comment out the `raise` above. If the retry ended up not doing any good, it’ll just re-raise the LoadError that was rescued.

Frankly, this probably isn’t very useful in practice. After all, if you cared about 1.8/1.9 compatibility, you could just require(“rubygems”) first and get rid of all of the exception handling. I think it’s a pretty good example of how `retry` works, though.

9 Comments more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...