April, 2012

2
Apr 12

Limiting IRB output

Below is a snippet from my .irbrc file on our production servers, which we access over SSH. It has saved so much frustration by truncating IRB output to 3000 characters. It will, of course, potentially break any code using printf…

module Colours
  Reset = "\e[0m"
  Red = "\e[0;31m"
  Green = "\e[0;32m"
  Yellow = "\e[0;33m"
  Blue = "\e[0;34m"
  Magenta = "\e[0;35m"
  Cyan = "\e[0;36m"
  White = "\e[0;37m"
  BrightRed = "\e[1;31m"
  BrightGreen = "\e[1;32m"
  BrightYellow = "\e[1;33m"
  BrightBlue = "\e[1;34m"
  BrightMagenta = "\e[1;35m"
  BrightCyan = "\e[1;36m"
  BrightWhite = "\e[1;37m"
end

# Only print the first 3000 characters using printf().
#
# It would be nicer to only do this for instances of IRB::Irb, but I can't work
# out how to do that in .irbrc or files required there.
module Kernel
  alias_method :old_printf, :printf

  def printf(*args)
    if args.last.length > 3000
      args.last.slice! 3000...args.last.length
      args.last << "#{Colours::BrightCyan} ...\n  ... etc#{Colours::Reset}"
    end
    old_printf *args
  end
end

I don't understand why something like the snippet below isn't the default:

require "bigdecimal"

class BigDecimal
  def inspect
    "#{Colours::BrightMagenta}#{to_s}#{Colours::Reset} (BD)"
  end 
end