
Rails Callbacks: 5 Best Practices Used at Gusto - whalesalad
https://medium.com/gusto-engineering/rails-callbacks-5-best-practices-used-at-gusto-7df1094f19fd
======
ejlangev
I worked with Rails for a number of years and generally agree with the ideas
in this post about finding callbacks to be confusing. Our guideline was to
only use ActiveRecord models for direct validation and attribute manipulation
and never as a way to hold logic. We also found that it greatly simplified
things to move the behavior into service objects.

It's worth noting, however, that not everyone agrees with this approach. DHH
thinks that it's clearer to use concerns and callbacks than service objects in
most cases. Worth watching his "Writing Software Well" video series
([https://www.youtube.com/watch?v=m1jOWu7woKM](https://www.youtube.com/watch?v=m1jOWu7woKM))
for an alternative perspective where you can look at some real, production
Basecamp code and see how his viewpoint looks in practice.

------
ExactoKnight
Like the idea about after_commit callbacks. There's nothing nastier than a
valid object saving (especially one calling an API somewhere else), and then
that save rolling back due to a callback exception.

A good rule of thumb I heard about Model callbacks is they should only be used
to persist or modify state about _themselves._ I.e. creating and persisting
many other ActiveRecord relations, in response to a callback, is a road to
misery.

I will also comment more generally that I believe notifications + callbacks is
a very difficult area of Rails architecture that is not well handled in the
MVC approach it provides.

I would look to Rails event store as a path for decoupling service objects
even more, from the sequential actions that lead to their creation.

