KNgu KNgu - 5 months ago 8
Ruby Question

Callback for puts and warn Ruby

I am trying to have a callback for all iterations of puts (puts, p) and warn.

For example:

puts "test" -> def callback() -> "test"

How would I be able to achieve this?


You can do this, but be really sure you want to, because it will apply to the entire Ruby runtime whenever you do. If you are working on a project with other people, be sure to get their buy-in.

To do this, you alias the original method to an additional method name. Then you redefine the method to do your own processing, which I presume ends with calling the original method. For example, for puts:

#!/usr/bin/env ruby

module Kernel
    alias original_puts puts
    def puts(object)
        # Do my own processing here, e.g.
        original_puts "This is coming from my overrided puts:"

puts 'hi'



This is coming from my overrided puts: