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

Background Color Methods 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 or when the NO_COLOR env variable is set, 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)


1007
1008
1009
# File 'lib/command_kit/colors.rb', line 1007

def ansi?(stream=stdout)
  env['TERM'] != 'dumb' && !env['NO_COLOR'] && 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.



1027
1028
1029
1030
1031
1032
1033
1034
# File 'lib/command_kit/colors.rb', line 1027

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

  yield color if block_given?
  return color
end