Re:Ruby 2.0.0 Released
by Mon_Ouie on Monday February 25, 2013 @05:51AM
(#5278287)
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.
For example, say I have a class that can process stuff, and a mixin that attempts to log calls to the #process method:
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.