Module: Treequel::ANSIColorUtilities

Included in:
ColorLogFormatter
Defined in:
lib/treequel/mixins.rb

Overview

A collection of ANSI color utility functions

Constant Summary collapse

ANSI_ATTRIBUTES =

Set some ANSI escape code constants (Shamelessly stolen from Perl’s Term::ANSIColor by Russ Allbery <[email protected]> and Zenin <[email protected]>

{
	'clear'      => 0,
	'reset'      => 0,
	'bold'       => 1,
	'dark'       => 2,
	'underline'  => 4,
	'underscore' => 4,
	'blink'      => 5,
	'reverse'    => 7,
	'concealed'  => 8,

	'black'      => 30,   'on_black'   => 40,
	'red'        => 31,   'on_red'     => 41,
	'green'      => 32,   'on_green'   => 42,
	'yellow'     => 33,   'on_yellow'  => 43,
	'blue'       => 34,   'on_blue'    => 44,
	'magenta'    => 35,   'on_magenta' => 45,
	'cyan'       => 36,   'on_cyan'    => 46,
	'white'      => 37,   'on_white'   => 47
}

Class Method Summary collapse

Class Method Details

.ansi_code(*attributes) ⇒ Object

Create a string that contains the ANSI codes specified and return it



346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/treequel/mixins.rb', line 346

def ansi_code( *attributes )
	attributes.flatten!
	attributes.collect! {|at| at.to_s }
	return '' unless /(?:vt10[03]|xterm(?:-color)?|linux|screen)/i =~ ENV['TERM']
	attributes = ANSI_ATTRIBUTES.values_at( *attributes ).compact.join(';')

	if attributes.empty?
		return ''
	else
		return "\e[%sm" % attributes
	end
end

.colorize(*args) ⇒ Object

Colorize the given string with the specified attributes and return it, handling line-endings, color reset, etc.



362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/treequel/mixins.rb', line 362

def colorize( *args )
	string = ''

	if block_given?
		string = yield
	else
		string = args.shift
	end

	ending = string[/(\s)$/] || ''
	string = string.rstrip

	return ansi_code( args.flatten ) + string + ansi_code( 'reset' ) + ending
end