How to 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 that I want to make available to a third-party class and its clients. They are the open interface of the mixin module.

But I want some other methods and instance variables to be encapsulated. I don’t want them to be available for the class I am mixing into, and in particular, I don’t want them to accidentally override shadow conflicts or otherwise interfere with mixer class methods or instance variables — or those that may currently exist time, or those that may be created in the future if the third-party changes the class I am mixing into.

What precautions should I take, if any, to ensure that my mixin is “hygienic” in this way?

+5
source share
2 answers

Create a separate object to encapsulate your functionality and instance variables, and let mixin delegate public methods to this object. Now you need to associate only one instance variable with your object. You can even avoid this by storing the hash {Mixee => Delegate} in the module and doing a search at the beginning of each mixed method.

+2
source

Perhaps you could create a submodule to contain all the useful utilities.

module Foo
  module Utils
    def self.answer
      42
    end
  end
  def helpme
    "the answer is #{Utils.answer}"
  end
end
include Foo
puts helpme
+1
source

All Articles