Let’s get the naming thing out of our way first: metaclasses, virtual classes or eigenclasses all refer to the same thing. Since Ruby 1.9.2, Object has a method #singleton_class, and that is how I will call it for the rest of this post. The proximity to the Singleton Pattern is no coincidence, singleton classes do have exactly one “instance”.

We know that singleton classes somehow sit between an instance and its class, refining behavior defined in the class just for this very instance. In most projects, creating different classes for objects having different behavior does the trick. There is no need for those singleton classes.

What we commonly call class methods, technically are (singleton) instance methods of class objects, defined in their respective singleton classes.

We see that each class in Ruby has a corresponding singleton class (which holds the so-called class methods). Both follow the same inheritance line, and both are instances of Class (Go play around yourself in IRB with #class, #singleton_class and #superclass to figure out how the model continues from there).

This twofold hierarchy means that you can leverage the same inheritance potential for class methods as you can for instance methods, like method overriding or calling super. Generic class methods like ActiveRecord::Base.find may be implemented in abstract super classes, returning results specific to the concrete class the method is eventually called on. I am sure there are various cases where you applied such class-side goodness but never though of the singleton classes and their parallel hierarchy involved.

References

The Real Use of Ruby Singleton Classes : Puzzle ITC
https://www.puzzle.ch/blog/articles/2017/12/11/the-real-use-of-ruby-singleton-classes

打赏

Leave a Reply

Your email address will not be published. Required fields are marked *