Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a hygienic Ruby mixin?

Say I'm writing a mixin module that adds functionality to a third-party class. Obviously some of the methods and instance variables I want to make accessible to the third-party class and its clients. These constitute the public interface of the mixin module.

But I want certain other methods and instance variables to be encapsulated. I don't want them to be accessible to the class I'm mixing into, and in particular I don't want them to accidentally override, shadow, conflict, or otherwise interfere with the mixee class's methods or instance variables -- either those that may currently exist, or those that may be created in the future if the third-party modifies the class I'm mixing into.

What precautions do I need to take, if any, to make sure my mixin is "hygienic" in this way?

like image 700
John Avatar asked Oct 26 '22 03:10

John


1 Answers

Create a separate object to encapsulate your functionality and instance variables, and have the mixin delegate the publically accessible methods to that object. Now you only need to associate a single instance variable with your object. You could even dodge that by storing a {Mixee => Delegate} Hash in the module and doing a lookup at the start of each mixed in method.

like image 51
rampion Avatar answered Oct 30 '22 00:10

rampion