Last active
December 30, 2023 00:35
-
-
Save iax7/9895052e4a72ad736064140b710323d0 to your computer and use it in GitHub Desktop.
Simple class to generate ANSI Color output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @example basic usage | |
# Color.blue => "\e[1;34m" | |
# @example chain bold | |
# Color.red.bold => "\e[1;31m" | |
class Color | |
NORMAL = 30 | |
BRIGHT = 90 | |
BG_DIFF = 10 | |
CODES = { | |
black: 0, | |
red: 1, | |
green: 2, | |
yellow: 3, | |
blue: 4, | |
magenta: 5, | |
cyan: 6, | |
white: 7 | |
}.freeze | |
def initialize(code) | |
@code = code | |
@modifier = nil | |
end | |
def bold | |
@modifier = 1 | |
self | |
end | |
def to_s | |
modifier = @modifier ? "#{@modifier};" : '' unless @code.zero? | |
"\e[#{modifier}#{@code}m" | |
end | |
def inspect | |
"<#{self.class} code=#{@code} mod=#{@modifier.inspect}>" | |
end | |
define_singleton_method(:reset) { new 0 } | |
CODES.each do |color, code| | |
define_singleton_method(color) { new(code + NORMAL) } | |
define_singleton_method("bright_#{color}") { new(code + BRIGHT) } | |
define_singleton_method("bg_#{color}") { new(code + NORMAL + BG_DIFF) } | |
define_singleton_method("bg_bright_#{color}") { new(code + BRIGHT + BG_DIFF) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment