[Feature Request] async option for after_commit ActiveRecord hook

162 views
Skip to first unread message

Chad Wilken

unread,
Nov 22, 2017, 5:53:22 PM11/22/17
to Ruby on Rails: Core
I have quite a few places where I enqueue a job in an after_commit hook but the job just re-instantiates the object and calls a method on it. It would be handy if you could pass async: true to the callback to have it executed asynchronously. Before writing the code and opening a pull request I wanted to see if this would be of use to anyone else.

The way I see it working:

class Post < ApplicationRecord
  after_commit
:notify_subscribers, on: :create, async: true

 
private

 
def notify_subscribers
   
# Some long running code that needs to be async
 
end
end

class AsyncCallbackJob < ApplicationJob
 
def perform(record, method)
    record
.send(method)
 
end
end


Xavier Noria

unread,
Nov 25, 2017, 4:12:26 PM11/25/17
to rubyonra...@googlegroups.com
There’s something that makes me wonder: this async option probably makes sense only in after_commit callbacks, because it seems rare that you want to run something later even if there’s a rollback. So, the generic “Callback” name in the proposed job class is really not so generic in reality.

Taking that into account, I see this proposal as a too exceptional API to deserve being in core.

Of course, you could decorate after_commit in ApplicationRecord to do what you want if async is present and delegate to super.

--
Sent from Gmail Mobile

Chad Wilken

unread,
Nov 27, 2017, 10:40:49 AM11/27/17
to Ruby on Rails: Core
Sounds good, that makes sense.
Reply all
Reply to author
Forward
0 new messages