This article mainly introduces the example of Ruby optimization inheritance class, this article directly gives an example of optimization and implementation code, the need for friends can refer to the following
In the rails principle there is the idea of simplifying controller, enriching model. A simple inheritance optimization is shown below with an example. Especially when you have a change self variable in your method.
Suppose we have the following model
The code is as follows:
Class Subjectmatterexpert < User
Include Hashcodecreatormodule
def Make_activation_code
Self.deleted_at = Nil
Self.activation_code | | = Make_hash_code
End
End
Class Administrator < User
Include Hashcodecreatormodule
def Make_activation_code
Self.deleted_at = Nil
Self.activation_code | | = Make_hash_code
End
End
We can simplify the code by inheriting using the following Subjectmatterexpert Administrator
The code is as follows:
Class Subjectmatterexpert < User
End
Class Administrator < User
End
Class User
Include Hashcodecreatormodule
def Make_activation_code
Self.deleted_at = Nil
Self.activation_code | | = Make_hash_code
End
Then we can use this in the test:
The code is as follows:
It ' should create a activation code ' do
admin = Factory (: Administrator)
Admin.make_activation_code
Admin.activation_code.should_not Be_empty
End