instance method define_model_callbacks

Ruby on Rails 3.1.12

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

define_model_callbacks(*callbacks)

define_model_callbacks accepts the same options define_callbacks does, in case you want to overwrite a default. Besides that, it also accepts an :only option, where you can choose if you want all types (before, around or after) or just some.

define_model_callbacks :initializer, :only => :after

Note, the :only => <type> hash will apply to all callbacks defined on that method call. To get around this you can call the define_model_callbacks method as many times as you need.

define_model_callbacks :create, :only => :after
define_model_callbacks :update, :only => :before
define_model_callbacks :destroy, :only => :around

Would create after_create, before_update and around_destroy methods only.

You can pass in a class to before_<type>, after_<type> and around_<type>, in which case the callback will call that class’s <action>_<type> method passing the object that the callback is being called on.

class MyModel
  extend ActiveModel::Callbacks
  define_model_callbacks :create

  before_create AnotherClass
end

class AnotherClass
  def self.before_create( obj )
    # obj is the MyModel instance that the callback is being called on
  end
end

Parameters

callbacks rest
Source
# File activemodel/lib/active_model/callbacks.rb, line 88
    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

Defined in activemodel/lib/active_model/callbacks.rb line 88 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveModel::Callbacks

Type at least 2 characters to search.

↑↓ navigate · open · esc close