Skip to content

Instantly share code, notes, and snippets.

@ccyrille
Last active February 2, 2020 15:01
Show Gist options
  • Save ccyrille/8221a0740bc655bc69835a087506833e to your computer and use it in GitHub Desktop.
Save ccyrille/8221a0740bc655bc69835a087506833e to your computer and use it in GitHub Desktop.
# This module allows to have an after_commit callback
# on a single AR instance. This is really useful in services.
#
# Usage example :
# mate = Mate.first
# mate.after_commit { |m| notify_first_name_changed(m) }
# mate.update_attributes!(first_name: "Gunter")
#
module ActiveRecord::InstanceCallbacks
def has_transactional_callbacks?
super || !@instance_after_commit_callback.nil?
end
def _run_commit_callbacks
super
return if @instance_after_commit_callback.nil?
@instance_after_commit_callback.call
end
#################################################
# Register instance after_commit callback
def after_commit(&block)
@instance_after_commit_callback = block
end
end
class ActiveRecord::Base
prepend ActiveRecord::InstanceCallbacks
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment