Refactoring Rails: Callbacks

WebDev Rails

I've abused callbacks enough to know they have limits. This post is some summarized notes on the recommendations for using callbacks effectively.

This post is notes from the fantastic course Refactoring Rails — If you are a rails dev, strongly recommend you check it out. 

Kinds of Callbacks + Tips


🟡 Transforming Data — Sanitizing phone numbers, emails etc 
Don't inline the details of this behavior, it's oftentimes helpful to create and call a service object, something like PhoneNumberSanitizer.new(phone_number) that way you've got a better place for all this to live. But calling the Sanitizer via a callback might not be the end of the world as long as you've got some good names, tests and separating your concerns where you can.

🟡 Updating Other Columns — Creating a random token, updating a field like "last_order_date" for a cached value
This can be a reasonable behavior, although it might be strange someone coming to the codebase that just creating an "Order" updates the "user" object. Be careful to not overuse or abuse these kinds of columns.

🛑 Side Effects — Sending out order confirmation email
This is so shitty. Really avoid this. It's super easy to accidentally trigger this kind of behavior. It's nice but very dangeroous. I once fired "Confirmation SMS's" to all of the production users running a rake task updating the customer. The answer to this is a Service Object in the controller, delegate the side effects to the service object. 




Similar Posts

Simple Full Text Search in Rails

No gems, no dependencies, no complexity. Here’s a basic full text search to use on simpler, smaller rails apps.

WebDev Rails

Refactoring Rails: Form Objects

Form objects let you work with many objects at once in rails. It's a pattern that's a lot more powerful and clean than accepts_nested_attributes.

WebDev Rails

Refactoring Rails: Use REST

Just some notes / key takeaways from the course "Refactoring Rails" by the great Ben Orenstein.

WebDev Rails