With the define_callbacks method, it's possible to define your own callbacks. The ActiveSupport::Callbacks module contains all the logic and implementations for defining events in the lifecycle of objects.
class MyModel < ActiveRecord::Base
define_callbacks :custom_callback
set_callback :custom_callback, :before do |record|
puts "before important_thing"
end
set_callback :custom_callback, :after do |record|
puts "after important_thing"
end
def important_thing
run_callback :custom_callback do
puts "...code"
end
end
end
MyModel.new.important_thing
The output:
before important_thing
...code
after important_thing
Top comments (0)