"Colorizing console output with Rainbow ruby gem"

March 24, 2009

If you’re working on some cool ruby console-based application or just want to add a little style to your script here is a nice gem for you. It’s called Rainbow and it extends ruby String class adding methods to wrap the string with ANSI escape codes.

Look at example irb session and see example usage:

Rainbow adds following methods to String class:

  • foreground(color) (with color and colour aliases)
  • background(color)
  • reset
  • bright
  • italic (not well supported by terminal emulators).
  • underline
  • blink
  • inverse
  • hide.

Color can be one of following symbols: :black, :red, :green, :yellow, :blue, :magenta, :cyan, :white and :default.

Each of those methods returns string wrapped with some ANSI codes so you can chain calls as in example above.

It also has Windows support (uses win32console gem if installed, otherwise strings are returned unaltered).

The gem is on rubyforge.org so install it by:

sudo gem install rainbow

and require it in your script.

The sources are on github, as usual.

Note: I know that there is similar gem on rubyforge called colored_. But, first, it adds too many methods to String class (the Rails way, method per color + method per background color + method per foregroundbackground color…). Second, as I had it already implemented creating a gem from this code was a snap, so why not do it?

Read more about console, gem, rainbow, ruby.
blog comments powered by Disqus