Module: ActiveSupport::Callbacks
- Extended by:
- Concern
- Defined in:
- lib/active_support/callbacks.rb
Overview
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
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
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
Defined Under Namespace
Modules: ClassMethods Classes: Callback, CallbackChain
Instance Method Summary collapse
Methods included from Concern
append_features, extended, included
Instance Method Details
#callback(kind) ⇒ Object
96 97 98 99 |
# File 'lib/active_support/callbacks.rb', line 96 def callback(kind) ActiveSupport::Deprecation.warn("callback is deprecated. Please use run_callbacks") send("_run_#{kind}_callbacks") end |
#run_callbacks(kind, *args, &block) ⇒ Object
92 93 94 |
# File 'lib/active_support/callbacks.rb', line 92 def run_callbacks(kind, *args, &block) send("_run_#{kind}_callbacks", *args, &block) end |