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
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 }
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
I follow this order:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With