class Undebug
  class << self

    def code_position(distance)
      begin
        raise "trace"
      rescue Exception => e
        e.backtrace[distance + 1]
      end
    end

    def trace_message(string)
      Kernel.module_eval do
        [:puts, :p, :print, :warn].each do |method|
          feature = "message_tracing"
          method_with = "#{method}_with_#{feature}"
          method_without = "#{method}_without_#{feature}"
          define_method method_with do |*args|
            send(method_without, *args).tap do |value|
              if args.first.is_a?(String) && args.first.include?(string)
                send("puts_without_message_tracing", "Printed '#{string}' at #{Undebug.code_position(3)}")
              end
            end
          end
          alias_method_chain method, feature
        end
      end
      send("puts_without_message_tracing", "Message tracing is active and slowing down the application! Disable me in #{Undebug.code_position(1)}.")
    end

  end
end
