-
-
Save PratheepV/45dd4cc3e001cb94d096 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_validation, AfterCommitCallbacks::Handlers) | |
base.send(:after_commit, AfterCommitCallbacks::Handlers) | |
end | |
module Handlers | |
def self.before_validation(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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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