Don't re-require 'rexml/document'
In what case will this make a difference?
require only loads files once if $LOAD_PATH is set up properly.
defined? is a zillion times faster than require
here is a bench that proves it: http://gist.github.com/24726
Thanks for the explanation!
Has anybody analysed and documented why require is so slow?
This is definitely double-take code. If it’s a one-off, how about a comment explaining why? If it’s not a one-off, it should probably be wrapped in a method (with an explanation there).
Another instance of the same pattern:
Here’s a list of all instances in rails/HEAD:
Run $LOAD_PATH.size in both a Rails console and normal irb then compare the results.
In addition to the size of the load path, there’s the gems that you have, and the fact that rubygems monkeypatches require so it’ll take a while longer.
The reality is we shouldn’t need to put this here, requiring in methods is nasty. Hopefully once the autoload changes settle down we can make this a little nicer.
As for DRYing it up, we can’t wrap it in a method anyway as defined? has special behaviour you can’t replicate in your own code
So this is not possible?
def require_unless_defined(library, class)
require library unless defined?(class)
No, it’s not.
>> require_unless_defined(“asdf”, REXML::Document)
NameError: uninitialized constant REXML
Okay, thanks. I was just curious. :)