File: codes.rb

package info (click to toggle)
ruby-colored2 4.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 560 kB
  • sloc: ruby: 345; makefile: 4
file content (65 lines) | stat: -rw-r--r-- 1,037 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: false

module Colored2
  COLORS = {
    black: 30,
    red: 31,
    green: 32,
    yellow: 33,
    blue: 34,
    magenta: 35,
    cyan: 36,
    white: 37
  }.freeze

  EFFECTS = {
    no_color: 0,
    bold: 1,
    dark: 2,
    italic: 3,
    underlined: 4,
    reversed: 7,
    plain: 21, # non-bold
    normal: 22
  }.freeze

  class Code
    attr_accessor :name, :escape

    def initialize(name)
      @name = name
      return if name.nil?

      @escape = codes[name.to_sym]
      raise ArgumentError, "No color or effect named #{name} exists for #{self.class}." if @escape.nil?
    end

    def value(shift = nil)
      escape_code = escape
      escape_code += shift if shift && escape_code
      name && escape ? "\e[#{escape_code}m" : ''
    end

    def to_s
      value
    end
  end

  class Effect < Code
    def codes
      EFFECTS
    end
  end

  class TextColor < Code
    def codes
      COLORS
    end
  end

  class BackgroundColor < TextColor
    def value
      super(10)
    end
  end
end