In this article, we’re going to explore the following topics:

inheritance and the instance method

method clone and dup methods

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

Inheritance and the instance method

In the previous article we’ve seen that after including the Singleton module, an instance method is implicitly defined within the including class

Here, the Singleton module defines the Ebook.instance method when it’s included in the Ebook class.

Cool! But what happens if a RubyObjectModel class inherits from the Ebook class ?

In the above example, the RubyObjectModel class inherits from the Ebook class.

As the Ebook class includes the Singleton module, then a RubyObjectModel.instance class method is implicitly defined.

So, the RubyObjectModel class defines its own version of the instance method and doesn’t use the one defined in the Ebook class.

This freshly defined method returns a uniq RubyObjectModel instance — and not an Ebook instance.

This mechanism allows the RubyObjectModel class to inherit from the behaviors of the Singleton module and the Ebook class while dealing with an independent RubyObjectModel instance.

So the inheritance principle is not broken, while the singleton pattern is persisted through inheritance.

Ok, this is cool! But when inheriting from a class that includes the Singleton module can be useful?

Here, we define a base class named Client that encapsulate a bunch of common attributes as url , port and credentials .

After, we define the DBClient and ApiClient classes that derivate from the Client class.

As only one instance of these classes is required to coordinate actions across the program, then making them inheriting from the Client class seems to be a good decision.

In effect, with this pattern the DBClient and the ApiClient :

include the Singleton module

module encapsulate common attributes

define common methods

clone and dup methods

When the Singleton module is included in a class then the Object#clone and Object#dup methods are overridden by the Singleton ones

In effect, these methods are redefined to raise an error.

This is due to the fact that, by essence, a uniq instance of a class shouldn’t be duplicable.

Otherwise, the Singleton module provides a clone class method that instantiate a new anonymous class.

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com