Rails ActiveRecord CALLBACKS constant processing: HOW?

Trying to find the source code of “after_commit” and “after_rollback” transactional callbacks, I stumbled upon this CALLBACKS constant definition inside the ActiveRecord::Callbacks module. It is an array with this form:

[
      :after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
      :before_save, :around_save, :after_save, :before_create, :around_create,
      :after_create, :before_update, :around_update, :after_update,
      :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
]

What I don’t get is what line of code in the whole Rails project process that array.

What in the end will loop over that array?

And, how can I make sense of what after_commit and after_rollback do?

I’m wondering this last one because I’m supporting an old 4.2 Rails app, which according a warning: those callbacks currently ignore errors but will not in the future. So planing on upgrading, I want to prepare my code to or manage the possible errors or behave explicitly the same as now (Ignoring the errors) when I do upgrade to a newer Rails.

Usually callbacks are run with meta-programming using run_callbacks, so you generally shouldn’t see direct references to after_commit, yet just :commit like run_callbacks(:commit) {...} OR run_callbacks :commit do ... end:

So, look for that instead. Check out the line that runs it in rails/activerecord/lib/active_record/transactions.rb here (for whatever reason, they are using a different more specialized version of run_callbacks that is _run_commit_callbacks):

By the way, it seems that ActiveRecord::Callbacks::CALLBACKS is only used for testing in activerecord/test/cases/callbacks_test.rb

Anyways, I did not do exhaustive research, yet just a quick look. I hope that was helpful to continue further.

1 Like