prepend
So far, we've discussed the include
, extend
, and module
methods and namespaces. There is one more aspect to modules that came with the Ruby 2.0 release several years ago: prepend
. prepend
is not often used, perhaps because it is not well understood. Let's change that.
First, let's consider the following example:
module ClassLogger def log(msg) "[#{self.class}] #{msg}" end end class User include ClassLogger def log(msg) "[#{Time.now.to_f.to_s}] #{super(msg)}" end end class Company prepend ClassLogger def log(msg) "[#{Time.now.to_f.to_s}] #{super(msg)}" end end
We've created a module called ClassLogger
, which implements a log
method. This method wraps a string and outputs the current class. We've also created two classes, Company
and User
, which...