Thursday, July 16, 2009

Rails modeling guide#1: right structure of a ruby on rails model

30MAR4U

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:-

  1. CONSTANTS
  2. has_one, has_many, belongs_to, has_and_belongs_to relations in dependency order
  3. plug-ins initialization (acts_as_tree, acts_as_state_machine etc.)
  4. validates_presence_of
  5. validates_uniqueness_of
  6. validates_numericality_of
  7. validates_format_of
  8. custom_validations
  9. named_scopes grouped by related purposes
  10. active record hooks (after_initialize, before_create, after_create, ...) in execution order in the format (after_initialize [:assign_default_state, :sanitize_content] )
  11. protected
  12. hook method implementations according to execution order
  13. public
  14. constructor
  15. class methods in alphabetic order
  16. other methods alphabetically or grouped if related
  17. protected
  18. methods alphabetically or grouped if related
  19. private
  20. 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?

  1. We are absolutely sure where to look for a method or where to write a new method.
  2. The code base is really consistent.
  3. The unit test methods also follow the same order, which makes managing the test suite easy.

More to come later this week. Stay tuned!