Skip to content

Instantly share code, notes, and snippets.

@lacco
Created April 15, 2012 13:00
Show Gist options
  • Save lacco/2392664 to your computer and use it in GitHub Desktop.
Save lacco/2392664 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_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
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
@PratheepV
Copy link

after_update_on_update is triggered for new records.

to reproduce the issue

  class User < ActiveRecord::Base
  end
  class UserObserver < ActiveRecord::Observer
    def after_commit_on_create 
      puts 'on create'
    end
    def after_commit_on_update
      puts 'on update'
    end
  end

  User.new.save(:validate => false)

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 to before_save.

Thanks,
Pratheepv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment