Avoid God classes in Rails
One way to avoid classes with too much knowledge of our domain is to have asymmetrical ActiveRecord associations.
Eg. In our billing system, we have a set of invoices which are related to a specific account. Just do:
class Invoice < ActiveRecord::Base
belongs_to :account
def self.by_account(account)
where(account_id: account.id)
end
end
Note that we didn't declared an account to have many invoices, because this class shouldn't be aware of this concept.
This has an impact on how we're used to use AR APIs: from account.invoices
to Invoice.by_account(account)
, that can be a bit noisy, but for sure has the clear advantage of keeping your classes lighter.
Written by Luca Guidi
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#