Created
April 15, 2012 13:00
-
-
Save lacco/2392664 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
after_update_on_update is triggered for new records.
to reproduce the issue
If I change the code it worked for me. But I am not sure will it going to break in some other place. So, Please review my changes,
https://gist.github.com/PratheepV/228d0ab4abeb490370e3
Here I just changed
before_validate
tobefore_save
.Thanks,
Pratheepv