Question

I am building a gem which will append a particular string to every puts output. A use case might look like this:

string_to_append = " hello world!"
puts "The web server is running on port 80"
# => The web server is running on port 80 hello world!

I am not sure how to do this. A pseudo-code of it might be something like this:

class GemName
  def append
    until 2 < 1
        if puts_is_used == true
            puts string << "hello world!"
        else
            puts ""
        end
    end
  end
end

Any insight into the best approach regarding how to do this is very much appreciated.

Was it helpful?

Solution

This can easily be done with aliasing. I'd say that this is a very common idiom for decorating methods.

# "open" Kernel module, that's where the `puts` lives.
module Kernel
  # our new puts
  def puts_with_append *args
    new_args = args.map{|a| a + ' hello world'}
    puts_without_append *new_args
  end

  # back up name of old puts
  alias_method :puts_without_append, :puts

  # now set our version as new puts
  alias_method :puts, :puts_with_append
end

puts 'foo'
# >> foo hello world

# it works with multiple parameters correctly
puts 'bar', 'quux'
# >> bar hello world
# >> quux hello world
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top