Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Don't re-require 'rexml/document'

  • Loading branch information...
commit 17940a82e8cb0ed278e1552b943dd033763978a1 1 parent 05a938c
@lifo lifo authored
Showing with 1 addition and 1 deletion.
  1. +1 −1  activesupport/lib/active_support/xml_mini.rb
2  activesupport/lib/active_support/xml_mini.rb
@@ -17,7 +17,7 @@ module XmlMini
# string::
# XML Document string to parse
def parse(string)
- require 'rexml/document'
+ require 'rexml/document' unless defined?(REXML::Document)
doc =
merge_element!({}, doc.root)

12 comments on commit 17940a8


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

sr commented on 17940a8

here is a bench that proves it:


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 from (irb):4


Okay, thanks. I was just curious. :)

Please sign in to comment.
Something went wrong with that request. Please try again.