Reopen with module_eval
Ruby has open classes, and that's cool. If you're partially defining a class and don't care whether other parts of the definition have already been loaded, then by all means take advantage of the fact that you can reopen using the same syntax you use to define in the first place.
class Sub < Base # this may create Sub or reopen it.
def asdf ... end
However, this is a pretty unusual case on a real project. Typically a class from a third-party library is reopened to modify its original implementation. Often a method is aliased or undefined. If the original definition hasn't been loaded already, the reopening won't accomplish its intent. Hopefully it will fail at some point during the reopening. If you're unlucky (for example if you're trying to replace a method by simply re-
def'ing) you may get through your code without an error, leaving you with a very difficult to find bug.
If you're reopening in this sort of situation, I recommend using
module_eval rather than a class-declaration-style reopening.
def asdf ... end
This way, if the original class definition hasn't already been loaded, your code will fail quickly and cleanly as soon as you try to touch the class (with a
NameError: uninitialized constant WhateverYouTriedToReopen) rather than more mysteriously some time later. (Always prefer failing fast and clean when practical.)
The benefit of this is even greater if you're working with Rails: If you try to call
class_eval on a class that hasn't been loaded yet, the
dependencies.rb will kick in and go looking for the class you're reopening, loading it just in time for you to bend it to your will.