Module: CommandKit::Colors

Includes:
Env, Stdio
Defined in:
lib/command_kit/colors.rb

Overview

Defines ANSI color codes.

Examples

include CommandKit::Colors

def run
  puts colors.green("hello world")
end

Printing color error messages

stderr.puts colors(stderr).red("error!")

Environment Variables

  • TERM - Specifies the type of terminal. When set to DUMB, it will disable color output.

Alternatives

Defined Under Namespace

Modules: ANSI, PlainText

Instance Attribute Summary

Attributes included from Env

#env

Instance Method Summary collapse

Methods included from Env

#initialize

Methods included from Stdio

#abort, #gets, #initialize, #print, #printf, #putc, #puts, #readline, #readlines, #stderr, #stdin, #stdout

Instance Method Details

#ansi?(stream = stdout) ⇒ Boolean

Note:

When the env variable TERM is set to dumb, it will disable color output. Color output will also be disabled if the given stream is not a TTY.

Checks if the stream supports ANSI output.

Parameters:

  • stream (IO) (defaults to: stdout)

Returns:

  • (Boolean)


358
359
360
# File 'lib/command_kit/colors.rb', line 358

def ansi?(stream=stdout)
  env['TERM'] != 'dumb' && stream.tty?
end

#colors(stream = stdout) {|color| ... } ⇒ ANSI, PlainText

Returns the colors available for the given stream.

Examples:

puts colors.green("Hello world")

Using colors with stderr output:

stderr.puts colors(stderr).green("Hello world")

Parameters:

  • stream (IO) (defaults to: stdout)

Yields:

  • (color)

Returns:

  • (ANSI, PlainText)

    The ANSI module or PlainText dummy module.



378
379
380
381
382
383
384
385
# File 'lib/command_kit/colors.rb', line 378

def colors(stream=stdout)
  color = if ansi?(stream) then ANSI
          else                  PlainText
          end

  yield color if block_given?
  return color
end