Skip to content

Running Callbacks

mosop edited this page Feb 2, 2017 · 22 revisions

The run_callbacks_for_* method calls a given block with invoking callbacks in the following phase order:

  1. before
  2. around
  3. on
  4. calling a given block
  5. around
  6. after
class Record
  Callback.enable
  define_callback_group :save

  before_save do
    puts "before"
  end

  around_save do
    puts "around"
  end
  
  after_save do
    puts "after"
  end

  on_save do
    puts "on"
  end

  def save
    run_callbacks_for_save do
      puts "yield"
    end
  end
end

rec = Record.new
rec.save

This prints:

before
around
on
yield
around
after

Accessing an Instance in Callbacks

You can access a T instance by the first argument in callbacks.

class Record
  Callback.enable
  define_callback_group :save

  before_save do |o|
    o.validate
  end

  def validate
    puts "validate"
  end

  def save
    run_callbacks_for_save do
      puts "save"
    end
  end
end

rec = Record.new
rec.save

This prints:

validate
save
Clone this wiki locally