DEV Community

luiz filipe neves
luiz filipe neves

Posted on

Defining Your Own Callbacks in RoR

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
Enter fullscreen mode Exit fullscreen mode

The output:

before important_thing
...code
after important_thing
Enter fullscreen mode Exit fullscreen mode

Top comments (0)