Skip to content

Instantly share code, notes, and snippets.

@PratheepV
Forked from lacco/after_commit_callbacks.rb
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PratheepV/228d0ab4abeb490370e3 to your computer and use it in GitHub Desktop.
Save PratheepV/228d0ab4abeb490370e3 to your computer and use it in GitHub Desktop.
module AfterCommitCallbacks
def self.included(base)
base.send(:extend, ObserverCallbacks) unless base.respond_to?(:define_model_callbacks_for_observers)
[:create, :update, :destroy].each do |action|
base.send(:define_model_callbacks_for_observers, :"commit_on_#{action}", :only => :after)
end
base.send(:attr_accessor, :newly_created)
base.send(:before_save, AfterCommitCallbacks::Handlers)
base.send(:after_commit, AfterCommitCallbacks::Handlers)
end
module Handlers
def self.before_save(record)
record.newly_created = record.new_record?
true
end
def self.after_commit(record)
action = record.destroyed? ? "destroy" : (record.newly_created ? "create" : "update")
record.run_callbacks :"commit_on_#{action}"
true
rescue Exception => ex
p ex
raise ex
end
end
end
module ObserverCallbacks
# Calls define_model_callbacks and notify observers when called
def define_model_callbacks_for_observers(*args)
types = Array.wrap(args.extract_options![:only] || [:before, :around, :after])
callbacks = define_model_callbacks(*args)
callbacks.each do |callback|
types.each do |filter|
set_callback(callback, filter) do
notify_observers :"#{filter}_#{callback}"
true
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment