Flowdock

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
Show files where this module is defined (1 file)
Register or log in to add new notes.