csup - Crystal rewrite of sup email client

Singleton Classes
Login

Singleton Classes

As I mentioned in Ruby 3 Problems, Sup is filled with singleton classes. When I first encountered this programming pattern, my initial reaction was disgust, and I vowed never to use such a pattern in my own code. In fact, singletons do seem to have a bit of controversy around them, judging from the discussions I see on Stackoverflow.

But trying to port Sup without singletons looked like an overwhelming task: they're everywhere, and trying to rewrite them as normal classes was a daunting task.

So the question became: how to implement singletons in Crystal? In Sup, they are implemented with two things:

The method_missing feature makes clever use of Ruby's dynamic features: it defines a method with the missing name, and binds that method to the single instance of the class. This can't be done in Crystal, in which all methods must be known at compile time.

My solution was to implement a hack using some macros:

For more details, see the src/singleton.cr file in the source repository.