Module: XCPerfect::ANSI

Included in:
Bar, Formatter
Defined in:
lib/xcperfect/ansi.rb

Overview

ANSI applies color & style to the output to make it look more appealing to the eye

Constant Summary collapse

FORMATTED_MATCHER =
%r{\e\[(\d+)[;]?(\d+)?m(.*)\e\[0m}
EFFECT =
{
  reset: '0',
  bold: '1',
  underline: '4'
}.freeze
COLORS =
{
  black: '30',
  red: '31',
  green: '32',
  yellow: '33',
  blue: '34',
  cyan: '36',
  white: '37',
  plain: '39'
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#colorizeObject

Returns the value of attribute colorize.



5
6
7
# File 'lib/xcperfect/ansi.rb', line 5

def colorize
  @colorize
end

Instance Method Details

#ansi_parse(text, color, effect = nil) ⇒ Object



78
79
80
81
82
83
# File 'lib/xcperfect/ansi.rb', line 78

def ansi_parse(text, color, effect=nil)
  return text unless colorize?
  colors_code = COLORS[color] || ''
  effect_code = EFFECT[effect] ? ';' + EFFECT[effect] : ''
  "\e[#{colors_code}#{effect_code}m#{text}\e[#{EFFECT[:reset]}m"
end

#applied_effects(text) ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'lib/xcperfect/ansi.rb', line 63

def applied_effects(text)
  effects = []
  if text =~ FORMATTED_MATCHER
    colors = COLORS.invert[$1]
    effect = EFFECT.invert[$2]
    effects << colors if colors
    effects << effect if effect
  end
  effects
end

#color_for(percentage) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/xcperfect/ansi.rb', line 30

def color_for(percentage)
  case (percentage * 100).round
  when 0..33
    ->(x) { red(x) }
  when 33...66
    ->(x) { yellow(x) }
  when 66..100
    ->(x) { green(x) }
  else
    raise "Percentage of #{percentage * 100} is not possible"
  end
end

#colorize?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/xcperfect/ansi.rb', line 26

def colorize?
  !!@colorize
end

#cyan(text) ⇒ Object



55
56
57
# File 'lib/xcperfect/ansi.rb', line 55

def cyan(text)
  ansi_parse(text, :cyan)
end

#green(text) ⇒ Object



51
52
53
# File 'lib/xcperfect/ansi.rb', line 51

def green(text)
  ansi_parse(text, :green, :bold)
end

#red(text) ⇒ Object



47
48
49
# File 'lib/xcperfect/ansi.rb', line 47

def red(text)
  ansi_parse(text, :red)
end

#strip(text) ⇒ Object



74
75
76
# File 'lib/xcperfect/ansi.rb', line 74

def strip(text)
  text =~ FORMATTED_MATCHER ? $3 : text
end

#white(text) ⇒ Object



43
44
45
# File 'lib/xcperfect/ansi.rb', line 43

def white(text)
  ansi_parse(text, :plain, :bold)
end

#yellow(text) ⇒ Object



59
60
61
# File 'lib/xcperfect/ansi.rb', line 59

def yellow(text)
  ansi_parse(text, :yellow)
end