June 21, 2017
tl;dr - Just avoid them at all costs
Callbacks are evil. Well, maybe at this point in time, you haven’t realized that yet but I want you to read on and continue.
Consider this scenario.
class Message < ActiveRecord::Base after_commit :send_email, on: :create after_create :add_to_history, on: :create end
This is a simple representation of a model called
Message that has two(2)
send_emailwhich will obviously send an email.
add_to_historywhich will add a history item for tracking the user’s activity.
At first look, this seems to be a well-written code. Technically, it is but in reality it’s not and here’s why.
createa Message inside the Rails console?
Problem is the
Message model is tightly coupled to sending an email and adding a history item and you
don’t want that.
Well, adding callbacks was easy and it had saved you an ample amount of time.
You should also consider the different problems this may cause. A model that is difficult to test likely needs to be refactored. These callbacks could soon be a problem when your codebase has gotten bigger. And you don’t want to come to a point where removing these callbacks could be difficult and may take a wasteful amount of time to do.
I do not recommend this solution because it adds a bit of complexity to your app. I would still suggest avoiding those methods but if there are serious time constraints, might as well do it.
I hope you have understand the several reasons why Rails callbacks are something you should avoid doing.
A good solution for this problem would be to add a Service Object which will be a part of a future post.
Hi, I'm Mark Chavez. Creator of Get Things Done, yamda, public_apis, js_issues, bitcoin_index and a whole bunch of open-source projects. Join me on my adventures as I unfold the good and bad bits about software writing. You can also follow me on twitter and github for more goodies. Also, I love #oss!