Module: Fastererer::Painter

Defined in:
lib/fastererer/painter.rb

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

.colorize?Boolean

Returns:

  • (Boolean)


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

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

  $stdout.tty?
end

.disable!Object



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

def self.disable!
  @disabled = true
end

.enable!Object

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



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

def self.enable!
  @disabled = false
end

.paint(string, color) ⇒ Object



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

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



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

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