Skip to content

Appending Callbacks

mosop edited this page Nov 24, 2016 · 34 revisions

A callback is a Proc object and invoked in the run_callbacks_for_* method. To set a callback to be invoked, append the callback into a callback group using appenders.

An appender is a method for appending callbacks to callback groups.

An appender is one of:

  • before
  • around
  • after
  • on

The names mean phases. The phases indicate when appended callbacks are invoked in run_callbacks_for_*. For more information about the phases, see Running Callbacks.

The default type of a callback is Proc(T, Nil). For more information callback types, see Specifying Callback Types.

class Record
  Callback.enable
  define_callback_group :save

  before_save ->(o : Record) {
    # ...
    nil
  }
end

Passing Blocks

You can also pass blocks to appenders instead procs. You can omit variables from an argument list. And you can leave out a return value if a result type of a callback is Nil.

class Record
  Callback.enable
  define_callback_group :save

  before_save do |o|
    # ...
    nil
  end

  # arguments are not needed.
  before_save do
    # ...
    nil
  end

  # nil is not needed too.
  before_save do
    # ...
  end
end
Clone this wiki locally