Module: Kitchen::Color

Defined in:
lib/kitchen/color.rb

Overview

Utility methods to help ouput colorized text in a terminal. The implementation is a compressed mashup of code from the Thor and Foreman projects.

Author:

Constant Summary collapse

ANSI =
{
  reset: 0, black: 30, red: 31, green: 32, yellow: 33,
  blue: 34, magenta: 35, cyan: 36, white: 37,
  bright_black: 90, bright_red: 91, bright_green: 92,
  bright_yellow: 93, bright_blue: 94, bright_magenta: 95,
  bright_cyan: 96, bright_white: 97
}.freeze
COLORS =
%w{
  cyan yellow green magenta blue bright_cyan bright_yellow
  bright_green bright_magenta bright_blue
}.freeze

Class Method Summary collapse

Class Method Details

.colorize(str, name) ⇒ String

Returns a colorized ansi escaped string with the given color.

Parameters:

  • str (String)

    a string to colorize

  • name (Symbol)

    a valid color representation, taken from Kitchen::Color::ANSI

Returns:

  • (String)

    an ansi escaped string if the color is valid and an unescaped string otherwise



58
59
60
61
# File 'lib/kitchen/color.rb', line 58

def self.colorize(str, name)
  color = escape(name)
  color.empty? ? str : "#{color}#{str}#{escape(:reset)}"
end

.escape(name) ⇒ String

Returns an ansi escaped string representing a color control sequence.

Parameters:

  • name (Symbol)

    a valid color representation, taken from Kitchen::Color::ANSI

Returns:

  • (String)

    an ansi escaped string if the color is valid and an empty string otherwise



44
45
46
47
48
49
# File 'lib/kitchen/color.rb', line 44

def self.escape(name)
  return "" if name.nil?
  return "" unless ANSI[name]

  "\e[#{ANSI[name]}m"
end