module ActiveModel::Callbacks
def self.extended(base)
def self.extended(base) base.class_eval do include ActiveSupport::Callbacks end end
def _define_after_model_callback(klass, callback) #:nodoc:
def _define_after_model_callback(klass, callback) #:nodoc: klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1 def self.after_#{callback}(*args, &block) options = args.extract_options! options[:prepend] = true options[:if] = Array.wrap(options[:if]) << "!halted && value != false" set_callback(:#{callback}, :after, *(args << options), &block) end CALLBACK end
def _define_around_model_callback(klass, callback) #:nodoc:
def _define_around_model_callback(klass, callback) #:nodoc: klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1 def self.around_#{callback}(*args, &block) set_callback(:#{callback}, :around, *args, &block) end CALLBACK end
def _define_before_model_callback(klass, callback) #:nodoc:
def _define_before_model_callback(klass, callback) #:nodoc: klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1 def self.before_#{callback}(*args, &block) set_callback(:#{callback}, :before, *args, &block) end CALLBACK end
def define_model_callbacks(*callbacks)
end
end
# obj is the MyModel instance that the callback is being called on
def self.before_create( obj )
class AnotherClass
end
before_create AnotherClass
define_model_callbacks :create
extend ActiveModel::Callbacks
class MyModel
that the callback is being called on.
case the callback will call that class's
You can pass in a class to before_
Would create +after_create+, +before_update+ and +around_destroy+ methods only.
define_model_callbacks :destroy, :only => :around
define_model_callbacks :update, :only => :before
define_model_callbacks :create, :only => :after
method as many times as you need.
that method call. To get around this you can call the define_model_callbacks
Note, the :only =>
define_model_callbacks :initializer, :only => :after
where you can choose if you want all types (before, around or after) or just some.
you want to overwrite a default. Besides that, it also accepts an :only option,
define_model_callbacks accepts the same options define_callbacks does, in case
def define_model_callbacks(*callbacks) options = callbacks.extract_options! options = { :terminator => "result == false", :scope => [:kind, :name], :only => [:before, :around, :after] }.merge(options) types = Array.wrap(options.delete(:only)) callbacks.each do |callback| define_callbacks(callback, options) types.each do |type| send(:"_define_#{type}_model_callback", self, callback) end end end