Module: Fastererer::Painter

Defined in:
lib/fastererer/painter.rb

Constant Summary collapse

COLOR_CODES =
{
  red: 31,
  green: 32
}.freeze

Class Method Summary collapse

Class Method Details

.colorize?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
# File 'lib/fastererer/painter.rb', line 38

def self.colorize?
  return false unless ENV.fetch('NO_COLOR', '').empty?
  return false if @disabled

  $stdout.tty?
end

.disable!Object



29
30
31
# File 'lib/fastererer/painter.rb', line 29

def self.disable!
  @disabled = true
end

.enable!Object

Re-enables colorization; production never calls this — exists so tests can reset state.



34
35
36
# File 'lib/fastererer/painter.rb', line 34

def self.enable!
  @disabled = false
end

.paint(string, color) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/fastererer/painter.rb', line 12

def self.paint(string, color)
  # Validate before short-circuit so bad color symbols surface even with --no-color/NO_COLOR.
  color_code = COLOR_CODES[color.to_sym]
  if color_code.nil?
    raise ArgumentError,
          "Color #{color} is not supported. Allowed colors are #{COLOR_CODES.keys.join(', ')}"
  end

  return string unless colorize?

  paint_with_code(string, color_code)
end

.paint_with_code(string, color_code) ⇒ Object



25
26
27
# File 'lib/fastererer/painter.rb', line 25

def self.paint_with_code(string, color_code)
  "\e[#{color_code}m#{string}\e[0m"
end