I wanted to use this approach in my own project in order to be able to put additional actions into the “save” model from my controller level. I took Tadman to the stage further and created a module that can be introduced into active classes of models:
module InstanceCallbacks extend ActiveSupport::Concern CALLBACKS = [:before_validation, :after_validation, :before_save, :before_create, :after_create, :after_save, :after_commit] included do CALLBACKS.each do |callback| class_eval <<-RUBY, __FILE__, __LINE__ #{callback} :run_#{callback}_instance_callbacks def run_#{callback}_instance_callbacks return unless @instance_#{callback}_callbacks @instance_#{callback}_callbacks.each do |callback| callback.call end end def #{callback}(&callback) @instance_#{callback}_callbacks ||= [] @instance_#{callback}_callbacks << callback end RUBY end end end
This allows you to enter a complete set of instance callbacks into any model by simply turning on the module. In this case:
class Message include InstanceCallbacks end
And then you can do things like:
m = Message.new m.after_save do puts "In after_save callback" end m.save!
source share