module ActiveModel::Callbacks
def self.extended(base) # :nodoc:
def self.extended(base) # :nodoc: base.class_eval do include ActiveSupport::Callbacks end end
def _define_after_model_callback(klass, callback)
def _define_after_model_callback(klass, callback) klass.define_singleton_method("after_#{callback}") do |*args, **options, &block| options.assert_valid_keys(:if, :unless, :prepend) options[:prepend] = true conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v| v != false } options[:if] = Array(options[:if]) + [conditional] set_callback(:"#{callback}", :after, *args, options, &block) end end
def _define_around_model_callback(klass, callback)
def _define_around_model_callback(klass, callback) klass.define_singleton_method("around_#{callback}") do |*args, **options, &block| options.assert_valid_keys(:if, :unless, :prepend) set_callback(:"#{callback}", :around, *args, options, &block) end end
def _define_before_model_callback(klass, callback)
def _define_before_model_callback(klass, callback) klass.define_singleton_method("before_#{callback}") do |*args, **options, &block| options.assert_valid_keys(:if, :unless, :prepend) set_callback(:"#{callback}", :before, *args, options, &block) end end
def define_model_callbacks(*callbacks)
NOTE: +method_name+ passed to +define_model_callbacks+ must not end with
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
passing the object that the callback is being called on.
in which case the callback will call that class's
You can pass in a class to before_
only.
Would create +after_create+, +before_update+, and +around_destroy+ methods
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.
on that method call. To get around this you can call the +define_model_callbacks+
Note, the only:
define_model_callbacks :initialize, only: :after
around or after) or just some.
:only option, where you can choose if you want all types (before,
in case you want to overwrite a default. Besides that, it also accepts an
+define_model_callbacks+ accepts the same options +define_callbacks+ does,
def define_model_callbacks(*callbacks) options = callbacks.extract_options! options = { skip_after_callbacks_if_terminated: true, scope: [:kind, :name], only: [:before, :around, :after] }.merge!(options) types = Array(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