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
Methods
Public Instance methods
callback(kind)
      # File activesupport/lib/active_support/callbacks.rb, line 96
96:     def callback(kind)
97:       ActiveSupport::Deprecation.warn("callback is deprecated. Please use run_callbacks")
98:       send("_run_#{kind}_callbacks")
99:     end
run_callbacks(kind, *args, &block)
      # File activesupport/lib/active_support/callbacks.rb, line 92
92:     def run_callbacks(kind, *args, &block)
93:       send("_run_#{kind}_callbacks", *args, &block)
94:     end