-1

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?

Ilya
  • 13,337
  • 5
  • 37
  • 53
KNgu
  • 355
  • 4
  • 11

1 Answers1

1

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
Keith Bennett
  • 4,722
  • 1
  • 25
  • 35
  • Would there be a better way? I am trying to to capture both stdout and stderr and send it via a HTTP POST. – KNgu May 06 '16 at 04:10
  • Why not create your own method that does the post and call that method instead? Are you sure you want every single call to puts, etc., to be sent as an HTTP POST? – Keith Bennett May 06 '16 at 04:15
  • Because i am planning to use it on multiple projects and rewriting every puts and warn would be daunting. – KNgu May 06 '16 at 05:24