Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/candelabra/extensions.rb

Overview

This is used to colorize the ouput.

Example usage

“foo”.red # => 033[0;31mfoo033[0m

This code was borrowed from github.com/stefanpenner/terminal-color A big thanks this was much more sophisticated than my naive approach.

class String

def red
  "\033[0;31m#{self}\033[0m"
end

end

If you need colorization in your app and don’t minde dependencies it is highly recomended that you use the terminal-color or rainbow gem.

Constant Summary collapse

COLORS =
{
  :black     => '0',
  :red       => '1',
  :green     => '2',
  :yellow    => '3',
  :blue      => '4',
  :magenta   => '5',
  :cyan      => '6',
  :white     => '7'
}
FORMAT_CODES =
{
  :bold      => '1',
  :italic    => '3',
  :underline => '4',
  :blink     => '5',
}

Instance Method Summary collapse

Instance Method Details

#ansi_formattedObject



38
39
40
41
42
43
44
45
46
# File 'lib/candelabra/extensions.rb', line 38

def ansi_formatted
  ansi_csi = "#{(0x1B).chr}["
  formats = {}
  FORMAT_CODES.each do |name, code|
    formats[name] = code if @properties[name]
  end
  formats[:color] = "3#{COLORS[@properties[:color]]}" if @properties[:color]
  "#{ansi_csi}#{formats.values.join(';')}m#{self}#{ansi_csi}m"
end

#make_colorized(color) ⇒ Object



48
49
50
51
52
# File 'lib/candelabra/extensions.rb', line 48

def make_colorized(color)
  @properties ||= {}
  @properties[:color] = color
  ansi_formatted
end