Rails Best Practice: Callbacks.

Minh Reigen
2 min readJan 2, 2018

--

Have you called your mom back?

As an engineer worked on a project for a while, s/he may notice that there are many callbacks in your models, controller, etc… added in over time. This adds much more effort in debugging, implementing new features and maintenance work in general. If you happen to run a company, this is a big red flag.

The general idea is to have as less callbacks as possible especially in the Models.

As Josh Clayton said in his post.

after_* callbacks on Rails models seem to have some of the most tightly-coupled code, especially when it comes to models with associations

The before_* callbacks are usually used to set up the object prior to saving. However, the after_* callbacks are called after the object is saved. The problem here is when the object is saved, its responsibility has been completed or fulfilled, the after_* callbacks are mostly executing logic outside of the object’s responsibility. This violates the Single Responsibility Principle

So, the simple rule is:

Use a callback only when the logic refers to state internal to the object.

If you enjoyed this article, please recommend it by hitting the clap icon that you’ll find at the bottom of this page so that more people can see it on Medium. Thanks! 🙏

--

--

No responses yet