Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
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
View
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 = REXML::Document.new(string)
merge_element!({}, doc.root)
end

12 comments on commit 17940a8

@qerub

In what case will this make a difference?

require only loads files once if $LOAD_PATH is set up properly.

@lifo
Collaborator

defined? is a zillion times faster than require

@sr
sr commented on 17940a8

here is a bench that proves it: http://gist.github.com/24726

@qerub

Thanks for the explanation!

Has anybody analysed and documented why require is so slow?

@henrik

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).

@qerub

Another instance of the same pattern: http://github.com/rails/rails/commit/27dbc27c4174974a318145d2dc6512457ea37241

@qerub

Here’s a list of all instances in rails/HEAD: http://pastie.textmate.org/private/nz0pnkfusyesyguofgunea

@defunkt

Run $LOAD_PATH.size in both a Rails console and normal irb then compare the results.

@NZKoz
Owner

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

@datra

So this is not possible?

def require_unless_defined(library, class)
  require library unless defined?(class)
end
@NZKoz
Owner

No, it’s not.

>> require_unless_defined(“asdf”, REXML::Document) NameError: uninitialized constant REXML from (irb):4

@datra

Okay, thanks. I was just curious. :)

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