Ruby Optimization Inheritance class instance

Source: Internet
Author: User
Tags inheritance

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.