=begin rdocThis extends string to allow colorization based on ANSIterminal codes. The following code actually came fromDmytro Shteflyuk's blog linked at end of this blogThanks to one of his readers for expanding it even further!Finally, here in the current incarnation on my machine.Usage: 'String content'.colorcolorize('string or text content', color_code)To get color code table, you simply call method ansi_color_table=endbeginrequire'Win32/Console/Ansi'ifPLATFORM=~/win32/rescueLoadErrorraise'You must gem install win32console to use color on Windows Console.'endclassStringdefred;colorize(self,"\e[1m\e[31m");enddefgreen;colorize(self,"\e[1m\e[32m");enddefdark_green;colorize(self,"\e[32m");enddefyellow;colorize(self,"\e[1m\e[33m");enddefyellow_on_black;colorize(self,"\e[1m\e[33m\e[40m");enddefyellow_on_drkred;colorize(self,"\e[1m\e[33m\e[41m");enddefblue;colorize(self,"\e[1m\e[34m");enddefdark_blue;colorize(self,"\e[34m");enddefpur;colorize(self,"\e[1m\e[35m");enddefcolorize(text,color_code)"#{color_code}#{text}\e[0m"endenddefansi_color_table[0,1,4,5,7].eachdo|attr|puts'----------------------------------------------------------------'puts"ESC[#{attr};Foreground;Background"30.upto(37)do|fg|40.upto(47)do|bg|print"\033[#{attr};#{fg};#{bg}m #{fg};#{bg} "endputs"\033[0m"endendreturnend
I have placed this file in my [ruby installation directory]\lib\ruby\site_ruby\1.8\ directory so it can be used as a library.
yellow_on_black and yellow_on_drkred are on the list for showing how to create additional ‘listed’ colors.
Easily extended list, and many, many applications.
The side affect of installing win32console is the added benefit of RSpec and Ruby DocTest being able to show actual colors in the output while testing, too.
So, fun toy for color, yes… practical, definitely!