In the Rails principle, there is a saying that simplifies the Controller and enriches the Model. Here is an example to show a simple inheritance optimization. Especially when there is a self variable that writes changes in your method.
Suppose we have the following Model
Copy the codeThe 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 use the simplified code through inheritance using the following SubjectMatterExpert Administrator
Copy the codeThe 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 also use it in the test:
Copy the codeThe code is as follows:
it 'should create an activation code' do
admin = Factory(:administrator)
admin.make_activation_code
admin.activation_code.should_not be_empty
end