module ActiveSupport::Callbacks

Callbacks are hooks into the life cycle of an object that allow you to trigger logic before or after an alteration of the object state.

Mixing in this module allows you to define callbacks in your class.

Example:

class Storage
  include ActiveSupport::Callbacks

  define_callbacks :save
end

class ConfigStorage < Storage
  set_callback :save, :before, :saving_message
  def saving_message
    puts "saving..."
  end

  set_callback :save, :after do |object|
    puts "saved"
  end

  def save
    run_callbacks :save do
      puts "- save"
    end
  end
end

config = ConfigStorage.new
config.save

Output:

saving...
- save
saved

Callbacks from parent classes are inherited.

Example:

class Storage
  include ActiveSupport::Callbacks

  define_callbacks :save

  set_callback :save, :before, :prepare
  def prepare
    puts "preparing save"
  end
end

class ConfigStorage < Storage
  set_callback :save, :before, :saving_message
  def saving_message
    puts "saving..."
  end

  set_callback :save, :after do |object|
    puts "saved"
  end

  def save
    run_callbacks :save do
      puts "- save"
    end
  end
end

config = ConfigStorage.new
config.save

Output:

preparing save
saving...
- save
saved

Public Instance Methods

callback(kind) click to toggle source
# File lib/active_support/callbacks.rb, line 97
def callback(kind)
  ActiveSupport::Deprecation.warn("callback is deprecated. Please use run_callbacks")
  send("_run_#{kind}_callbacks")
end
run_callbacks(kind, *args, &block) click to toggle source
# File lib/active_support/callbacks.rb, line 93
def run_callbacks(kind, *args, &block)
  send("_run_#{kind}_callbacks", *args, &block)
end