r/ruby • • Apr 10 '21

💎Ruby tip: Make your own callbacks using ActiveSupport::Callbacks

Do you know about the callbacks available in Rails controllers, models, mailboxes, action cable, middleware, etc? It's all using ActiveSupport's Callbacks module to do that. Well, you can make your own callbacks with it too!

Rough example on how to use the module

More complex, real-world example: StimulusReflex callbacks PR

31 Upvotes

8 comments sorted by

10

u/[deleted] Apr 10 '21

You can achieve same result with more simpler code than callback. I don't see the point of using callback here, callback are hard to debug, hard to test, vs a simple method taking a block.

2

u/websebdev Apr 11 '21

My example above was just to show roughly how to use the module. For a more real-world use case, check out my PR here in StimulusReflex where I added `before_reflex`, `after_reflex` and `around_reflex`: https://github.com/hopsoft/stimulus_reflex/pull/160
You will see that the boilerplate to set up the callbacks is hidden in the gem and that users of the gem can use these callbacks in a simple way.

Nonetheless, I generally agree with the points you mentioned about callbacks.

2

u/RICHUNCLEPENNYBAGS Apr 11 '21

Well, what if you're playing an elaborate prank on your coworkers?

34

u/[deleted] Apr 10 '21

Don't use callbacks, it's more indirection and makes code harder to read and test. Cool that the option exists for framework or library authors but you don't need to be using every shiny thing.

10

u/whitet73 Apr 10 '21

Came here to say this. Less callbacks, not more. That said I do appreciate the write-up

3

u/somazx Apr 10 '21

Good tip!

3

u/pau1rw Apr 10 '21

I did not know about this and I love it.