Rails models are no exception compared to the super models! You are in the business if and only if you got a good physical structure and can stick to it for years...
At Code71, we are keeping our rails models attractive following a few guidelines. I will be posting these guidelines in a series and here goes the first one - about the physical structure of the ruby on rails models.
We keep the following order consistent in our models:-
- has_one, has_many, belongs_to, has_and_belongs_to relations in dependency order
- plug-ins initialization (acts_as_tree, acts_as_state_machine etc.)
- named_scopes grouped by related purposes
- active record hooks (after_initialize, before_create, after_create, ...) in execution order in the format (after_initialize [:assign_default_state, :sanitize_content] )
- hook method implementations according to execution order
- class methods in alphabetic order
- other methods alphabetically or grouped if related
- methods alphabetically or grouped if related
- self methods in alphabetic order or similar methods in a group
other methods in alphabetic order or similar methods in a group
No method gets code real estate over 20 lines. If needed, one/more private methods are used.
How is this helping us?
- We are absolutely sure where to look for a method or where to write a new method.
- The code base is really consistent.
- The unit test methods also follow the same order, which makes managing the test suite easy.
More to come later this week. Stay tuned!