Hacker News new | ask | show | jobs
by Mon_Ouie 4862 days ago
A very common use case for Module#prepend is for mixins that want to decorate methods.

For example, say I have a class that can process stuff, and a mixin that attempts to log calls to the #process method:

     class Processor
       def process
         puts "Very important stuff here"
       end
     end

     module Logger
       def process
         puts "Entering process."
         super
         puts "Leaving process."
       end
     end
If you just ``include Logger`` in Processor it won't work: Processor#process is looked up before Logger#process. However, if you use Module#prepend, the ancestry chain will change and calls to Process#process will be decorated as expected.
1 comments

Thanks for the example.