Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common method order for Rails models [closed]

I'd like to keep my code tidy and follow the best practices amongst rails developers which leads me to this question. Let's say for instance I have the following method types for my model

  • Model Associations
  • Validations
  • Scopes
  • Callbacks
  • Other Custom Methods

What is the usual order that the above appear in? Please feel free to add any others I might've left out.

Bonus: Should you group variables alongside their associated method types or should all variables be grouped at the beginning of the model? Let's say I had a variable to store a regular expression. Is it best to keep it close to the validation(s) or at the top of the model similar to where you would keep globals?

Example:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, uniqueness: true, length: {within: 5..50}, format: { with: VALID_EMAIL_REGEX }
like image 720
Carl Edwards Avatar asked May 13 '26 21:05

Carl Edwards


2 Answers

It doesn't matter what convention you follow as long as you keep it consistent and easier for other developers to understand.

Commonly followed ordering would be

1. associations
2. scopes
3. class methods
4. validations
5. callbacks
6. instance methods

Some people also move class methods below callbacks. Again, its up to you. But keep it consistent

like image 157
usha Avatar answered May 15 '26 11:05

usha


I follow this order:

  1. associations
  2. scopes
  3. validations
  4. callbacks
  5. class methods
  6. instance methods

Again its really up to you and the important part is to BE CONSISTENT.

I put all variables in the beginning, you could put them anywhere but I think it advantageous to keep them together.

like image 41
ChrisBarthol Avatar answered May 15 '26 09:05

ChrisBarthol