instance method set_callback

Ruby on Rails 3.0.20

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

set_callback(name, *filter_list, &block)

Set callbacks for a previously defined callback.

Syntax:

set_callback :save, :before, :before_meth
set_callback :save, :after,  :after_meth, :if => :condition
set_callback :save, :around, lambda { |r| stuff; yield; stuff }

Use skip_callback to skip any defined one.

When creating or skipping callbacks, you can specify conditions that are always the same for a given key. For instance, in Action Pack, we convert :only and :except conditions into per-key conditions.

before_filter :authenticate, :except => "index"

becomes

dispatch_callback :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}

Per-Key conditions are evaluated only once per use of a given key. In the case of the above example, you would do:

run_callbacks(:dispatch, action_name) { ... dispatch stuff ... }

In that case, each action_name would get its own compiled callback method that took into consideration the per_key conditions. This is a speed improvement for ActionPack.

Parameters

name req
filter_list rest
block block
Source
# File activesupport/lib/active_support/callbacks.rb, line 479
      def set_callback(name, *filter_list, &block)
        mapped = nil

        __update_callbacks(name, filter_list, block) do |chain, type, filters, options|
          mapped ||= filters.map do |filter|
            Callback.new(chain, filter, type, options.dup, self)
          end

          filters.each do |filter|
            chain.delete_if {|c| c.matches?(type, filter) }
          end

          options[:prepend] ? chain.unshift(*(mapped.reverse)) : chain.push(*mapped)
        end
      end

Defined in activesupport/lib/active_support/callbacks.rb line 479 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::Callbacks::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close