Search code examples
rubystdoutstderr

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?


Solution

  • 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:"
            original_puts(object)
        end
    end
    
    puts 'hi'
    
    =begin
    
    Outputs:
    
    This is coming from my overrided puts:
    hi
    
    =end