Guys familiar with Rails are very likely used to the following code, and will not be surprised by it:
|
|
But actually the code is not as simple as it looks like, especially for the ones from Java or C# world.
In this piece of code, we can figure out that the class User
inherited the method find
from its parent class ActiveRecord::Base
(If you are doubt or interested in how it works, you can check this post Ruby Class Inheritance).
If you write the following code, it should works fine:
|
|
In Ruby’s world, most of the time you can replace a inheritance with a module mixin. So we try to refactor the code as following:
|
|
If we run the tests again, the 2nd test will fail:
|
|
The reason of the test failure is that the method ‘foo’ is not defined!
So it is interesting, if we inherits the class, the class method of base class will be available on the subclass; but if we include a module, the class methods on the module will be available on the host class!
As we discussed before(Ruby Class Inheritance), the module mixed-in is equivalent to include insert a anonymous class with module’s instance methods into the ancestor chain of child class.
So is there any way to make all tests passed with module approach? The answer is yes absolutely but we need some tricky thing to make it happen:
|
|