Class: Unmagic::Color::RGB::ANSI
- Inherits:
-
Object
- Object
- Unmagic::Color::RGB::ANSI
- Defined in:
- lib/unmagic/color/rgb/ansi.rb
Overview
ANSI SGR (Select Graphic Rendition) color code parsing.
Parses ANSI color codes used in terminal output. Handles standard 3/4-bit colors, 256-color palette, and 24-bit true color formats.
## Supported Formats
Standard 3/4-bit colors (foreground and background):
Unmagic::Color::RGB::ANSI.parse("31") # Red foreground
Unmagic::Color::RGB::ANSI.parse("41") # Red background
Unmagic::Color::RGB::ANSI.parse("91") # Bright red foreground
Unmagic::Color::RGB::ANSI.parse("101") # Bright red background
256-color palette:
Unmagic::Color::RGB::ANSI.parse("38;5;196") # Red foreground (256-color)
Unmagic::Color::RGB::ANSI.parse("48;5;196") # Red background (256-color)
24-bit true color:
Unmagic::Color::RGB::ANSI.parse("38;2;255;0;0") # Red foreground (true color)
Unmagic::Color::RGB::ANSI.parse("48;2;255;0;0") # Red background (true color)
Defined Under Namespace
Classes: ParseError
Class Method Summary collapse
-
.parse(input) ⇒ RGB
Parse an ANSI SGR color code.
-
.valid?(value) ⇒ Boolean
Check if a string or integer is a valid ANSI color code.
Class Method Details
.parse(input) ⇒ RGB
Parse an ANSI SGR color code.
Accepts SGR parameters only (not full escape sequences). Handles foreground and background colors in all formats. Integers are automatically converted to strings.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/unmagic/color/rgb/ansi.rb', line 91 def parse(input) raise ParseError, "Input must be a string or integer" unless input.is_a?(::String) || input.is_a?(::Integer) # Convert integers to strings input = input.to_s if input.is_a?(::Integer) # Strip and validate format clean = input.strip raise ParseError, "Can't parse empty string" if clean.empty? # Must be numeric with optional semicolons unless clean.match?(/\A\d+(?:;\d+)*\z/) raise ParseError, "Invalid ANSI format: #{input.inspect} (must be numeric with optional semicolons)" end # Split on semicolons parts = clean.split(";").map(&:to_i) parse_sgr_params(parts) end |
.valid?(value) ⇒ Boolean
Check if a string or integer is a valid ANSI color code.
58 59 60 61 62 63 |
# File 'lib/unmagic/color/rgb/ansi.rb', line 58 def valid?(value) parse(value) true rescue ParseError false end |