Recently we decided to make a general guideline for certain Rails3 project. And we experienced some troubles to formalize criteria: where code should be placed?
For models we end up with following:
Method should be added to the model if…
- it changes attributes of the model.
- it works as shortcut for long sequence of calls of model’s methods and has a good(semantic) name.
- it redefine some functionality.
- it needs to be inserted due to architectural issues.
Method should not be inserted if…
- it is used for representing data (except cases when Aggregations work).
- it is syntax sugar (syntax should be persistent)
- it returns constant value (use constants or class variables)
- it is alias for other method (use standard ruby ways to create aliases)
- it has more-less complex logic and does not change anything in the db (move it to the lib)
What also can be added as criterion? Which books\articles covers such questions?
I highly recommend that you read Rails Antipatterns: Best Practice Ruby on Rails Refactoring. A lot of what you’ve covered here is discussed, but it’s more of a best practices book. A lot of the topics are fairly obvious if you’ve been working with Rails for a while, but it’s a great resource for “checking-in” on your coding practices. I’ve lent it to other developers on my team and they’ve given really positive feedback on it.