koraktor's $stdout

Random snippets about programming and more

Ruby: Calling super constructors from multiple included modules

Ruby’s concept of modules and mixins is great. Every Ruby programmer will come to this conclusion – sooner or later.

There’s only one restriction that you may come across when working extensively with modules. Once you included several modules in another module or class you might still want to call constructors from multiple of this modules. Sadly Ruby’s super keyword won’t help you in this situation as it will only call one of the constructors. Once your class inherits from another class and includes two modules and you call super inside your class’ constructor, only initialize of the lastly included module will be called.1

Depending on your class and module hierarchy this might be completely fine. In some cases it’s nice to call multiple constructors2, though. Being in a mood to experiment, I tried to find the best way to call multiple constructors. The following code shows my final solution, which is a pretty simple and clean implementation of a “scoped super”.

  1. Ruby’s super is smart enough to check the arguments of the method candidates it might call, so super might even skip one or more of the super constructors.

  2. Please note that this also applies to other methods, but it will be most likely required for initialize.