This seems to be a popular interview question. It indeed requires advanced knowledge of ruby.
You have a class with a class method. Write a module that, when included, will override that class method.
Explanation of the problem
Now classic way of mixing in class methods is this (and it doesn’t solve the problem, of course).
module FooModule def self.included base base.extend ClassMethods end module ClassMethods def bar puts "module" end end end class Klass include FooModule def self.bar puts 'class' end end Klass.bar #=> class
When modules are included or extended into a class, its methods are placed right above this class’ methods in inheritance chain. This means that if we were to call super in that class method, it would print “module”. But we don’t want to touch original class definition, we want to alter it from outside.
So, can we do something?
Good for us, ruby has a concept of “open classes”. This means that we can change virtually everything in the app, even some 3rd-party libraries. Every class can “opened” and new methods can be added to it, or old methods can be redefined. Let’s look how it works. Read the rest of this entry »