Class: GollyUtils::Colourer

Inherits:
Object show all
Defined in:
lib/golly-utils/colourer.rb

Overview

Helps decorate text with ANSI colour codes.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output) ⇒ Colourer

Returns a new instance of Colourer.

Parameters:

  • output

    The target IO object that text will be written to.



8
9
10
# File 'lib/golly-utils/colourer.rb', line 8

def initialize(output)
  @output= output
end

Instance Attribute Details

#outputObject (readonly)

Returns the value of attribute output.



5
6
7
# File 'lib/golly-utils/colourer.rb', line 5

def output
  @output
end

Instance Method Details

#add_color(text, color_code) ⇒ String

Wraps text in a given colour code (with a colour-clear code on the end) if colours are enabled.

Returns:

  • (String)


30
31
32
# File 'lib/golly-utils/colourer.rb', line 30

def add_color(text, color_code)
  color_enabled? ? "#{color_code}#{text}\e[0m" : text
end

#color_enabled=(bool) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/golly-utils/colourer.rb', line 16

def color_enabled=(bool)
  # Ungracefully ripped out of RSpec.
  return unless bool
  @color = true
  if bool && ::RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
    unless ENV['ANSICON']
      warn "You must use ANSICON 1.31 or later (http://adoxa.110mb.com/ansicon/) to use colour on Windows"
      @color = false
    end
  end
end

#color_enabled?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/golly-utils/colourer.rb', line 12

def color_enabled?
  @color ||= output_to_tty?
end

#puts(text, color_code) ⇒ Object

Calls puts on the output stream with optionally coloured text.



35
36
37
# File 'lib/golly-utils/colourer.rb', line 35

def puts(text, color_code)
  output.puts add_color(text, color_code)
end