Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Honestly, I used to use the 1st form (reopening the class), as it feels more natural, but your question forced me to do some research on the subject and here's the result. </p> <p>The problem with reopening the class is that it'll silently define a new class if the original one, that you intended to reopen, for some reason wasn't defined at the moment. The result might be different:</p> <ol> <li><p>If you don't override any methods but only add the new ones and the original implementation is defined (e.g., file, where the class is originally defined is loaded) later everything will be ok.</p></li> <li><p>If you redefine some methods and the original is loaded later your methods will be overridden back with their original versions.</p></li> <li><p>The most interesting case is when you use standard <a href="http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-autoload">autoloading</a> or some fancy reloading mechanism (like the one used in Rails) to load/reload classes. Some of these solutions rely on <a href="http://ruby-doc.org/core-1.9.3/Module.html#method-i-const_missing">const_missing</a> that is called when you reference undefined constant. In that case autoloading mechanism tries to find undefined class' definition and load it. But if you're defining class on your own (while you intended to reopen already defined one) it won't be 'missing' any longer and the original might be never loaded at all as the autoloading mechanism won't be triggered.</p></li> </ol> <p>On the other hand, if you use <code>class_eval</code> you'll be instantly notified if the class is not defined at the moment. In addition, as you're referencing the class when you call its <code>class_eval</code> method, any autoloading mechanism will have a chance to locate class' definition and load it.</p> <p>Having that in mind <code>class_eval</code> seems to be a better approach. Though, I'd be happy to hear some other opinion.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload