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:-
- CONSTANTS
- 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.)
- validates_presence_of
- validates_uniqueness_of
- validates_numericality_of
- validates_format_of
- custom_validations
- 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] )
- protected
- hook method implementations according to execution order
- public
- constructor
- class methods in alphabetic order
- other methods alphabetically or grouped if related
- protected
- methods alphabetically or grouped if related
- private
- self methods in alphabetic order or similar methods in a group
other methods in alphabetic order or similar methods in a group
Rule
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!