Welcome, guest | Sign In | My Account | Store | Cart

This quick class extends the base String class to add the ability to chain escape codes onto your output. For instance: puts 'String'.bold.underline.blink.red for something truly hideous. Aside from the colors (all are supported, but I haven't put in support for background colors as of the time of this post), cursor placement (ymmv based on the term type), screen clearing, bold, underline, blink reverse, conceal are all handled as well.

Ruby, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class String
  # Normal colors
  def black;       colorize(self, "\e[0m\e[30");     end
  def red;         colorize(self, "\e[0m\e[31");     end
  def green;       colorize(self, "\e[0m\e[32");     end
  def yellow;      colorize(self, "\e[0m\e[33");     end
  def blue;        colorize(self, "\e[0m\e[34");     end
  def purple;      colorize(self, "\e[0m\e[35");     end
  def cyan;        colorize(self, "\e[0m\e[36");     end
  def white;       colorize(self, "\e[0m\e[37");     end

  # Fun stuff
  def clean;       colorize(self, "\e[0");           end
  def bold;        colorize(self, "\e[1");           end
  def underline;   colorize(self, "\e[4");           end
  def blink;       colorize(self, "\e[5");           end
  def reverse;     colorize(self, "\e[7");           end
  def conceal;     colorize(self, "\e[8");           end

  # Blanking
  def clear_scr;   colorize(self, "\e[2", mode="J"); end

  # Placement
  def place(line, column)
    colorize(self, "\e[#{line};#{column}", mode='f')
  end

  def save_pos;    colorize(self, "\e[", mode='s');  end
  def return_pos;  colorize(self, "\e[", mode='u');  end

  def colorize(text, color_code, mode='m')
    "#{color_code}#{mode}#{text}\e[0m"
  end

end

Reasons for wanting to colorize your output can be wildly varied, but it all really boils down to one thing. Keeping your eyes from bleeding as you frantically scan pages of grey text on a black background as they whiz by looking for anything out of the ordinary.

1 comment

This is also now available as a gem 'easy-color'.