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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay