module Callbacks

Ruby on Rails edge

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.11.3 v5.0.7.2 v5.1.7 v5.2.8.1 v6.0.6.1 v6.1.7.10 v7.0.10 v7.1.6 v7.2.4 v8.0.5.1 v8.1.4 edge

Active Model Callbacks

Provides an interface for any class to have Active Record like callbacks.

Like the Active Record methods, the callback chain is aborted as soon as one of the methods throws :abort.

First, extend ActiveModel::Callbacks from the class you are creating:

“‘ class MyModel

extend ActiveModel::Callbacks

end “‘

Then define a list of methods that you want callbacks attached to:

“‘ define_model_callbacks :create, :update “`

This will provide all three standard callbacks (before, around and after) for both the :create and :update methods. To implement, you need to wrap the methods you want callbacks on in a block so that the callbacks get a chance to fire:

“‘ def create

run_callbacks :create do
  # Your create action methods here
end

end “‘

Then in your class, you can use the before_create, after_create, and around_create methods, just as you would in an Active Record model.

“‘ before_create :action_before_create

def action_before_create

# Your code here

end “‘

When defining an around callback remember to yield to the block, otherwise it won’t be executed:

“‘ around_create :log_status

def log_status

puts 'going to call the block...'
yield
puts 'block successfully called.'

end “‘

You can choose to have only specific callbacks by passing a hash to the define_model_callbacks method.

“‘ define_model_callbacks :create, only: [:after, :before] “`

Would only create the after_create and before_create callback methods in your class.

NOTE: Defining the same callback multiple times will overwrite previous callback definitions.

Includes

Methods (defined here)

Private methods (3)

Show private methods Implementation detail — not part of the public API.

Used by

Extendd by (1)

Included by (1)

Methods (inherited)

From ActiveSupport::Callbacks (1)
From ActiveSupport::Concern (3)
From ActiveSupport::DescendantsTracker (3)

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close