Class: CapeCod::Color
- Inherits:
-
Object
- Object
- CapeCod::Color
- Defined in:
- lib/cape-cod/color.rb
Constant Summary collapse
- CODES =
The ANSI color codes.
{ black: 0, red: 1, green: 2, yellow: 3, blue: 4, magenta: 5, cyan: 6, white: 7, }.freeze
Class Method Summary collapse
-
.hex_to_ansi(hex) ⇒ Object
Returns the ANSI domain code for the given RGB color packed into an Integer.
Instance Method Summary collapse
-
#ansi_code ⇒ Object
Returns a string representing the ANSI escape code for this color.
-
#initialize(*color, ground) ⇒ Color
constructor
Initializes a the color.
Constructor Details
#initialize(*color, ground) ⇒ Color
Initializes a the color.
color may be either a single Integer representation of a RGB color, a Symbol with the color name (valid color names are listed in the COLORS hash), or three integers representing the RGB channels. ground is either :background or :foreground.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/cape-cod/color.rb', line 38 def initialize(*color, ground) unless [:foreground, :background].include? ground raise ArgumentError, 'color must be either foreground or background.' end if color.empty? || color.size > 3 || color.size == 2 raise ArgumentError, "wrong number of arguments (#{color.size + 1} for 2|4)." elsif color.size == 3 color = [(color[0] << 16) | (color[1] << 8) | color[2]] elsif color.first.is_a?(Integer) && color.first < 0 raise ArgumentError, 'hex code must be positive.' elsif color.first.is_a?(Symbol) && !CODES.has_key?(color.first) raise ArgumentError, %(invalid color name "#{color.first}".) end @ground = ground @color = color.first end |
Class Method Details
.hex_to_ansi(hex) ⇒ Object
Returns the ANSI domain code for the given RGB color packed into an Integer.
24 25 26 27 28 |
# File 'lib/cape-cod/color.rb', line 24 def self.hex_to_ansi(hex) (6 * ((hex >> 16 & 0xff) / 256.0)).to_i * 36 + (6 * ((hex >> 8 & 0xff) / 256.0)).to_i * 6 + (6 * ((hex & 0xff) / 256.0)).to_i end |
Instance Method Details
#ansi_code ⇒ Object
Returns a string representing the ANSI escape code for this color.
61 62 63 64 65 66 |
# File 'lib/cape-cod/color.rb', line 61 def ansi_code case @color when Symbol then code_from_name when Integer then code_from_hex end end |