Created
September 13, 2011 05:34
-
-
Save vderyagin/1213194 to your computer and use it in GitHub Desktop.
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
class ColorString < String | |
ABORT = "\e[0m" | |
ESC_SQS = { | |
:red => "\e[1m\e[31m", | |
:dark_red => "\e[31m", | |
:green => "\e[1m\e[32m", | |
:dark_green => "\e[32m", | |
:yellow => "\e[1m\e[33m", | |
:dark_yellow => "\e[33m", | |
:blue => "\e[1m\e[34m", | |
:dark_blue => "\e[34m", | |
:purple => "\e[1m\e[35m", | |
:bold => "\e[1m", | |
:blink => "\e[5m" | |
} | |
def initialize(string='', *effects) | |
super(string) | |
apply_effects! *effects | |
end | |
def apply_effects(*effects) | |
effects.inject { |eff, memo| decorate ESC_SQS[eff] } | |
end | |
def apply_effects!(*effects) | |
effects.each { |eff| decorate! ESC_SQS[eff] } | |
self | |
end | |
ESC_SQS.each do |key, value| | |
define_method(key) { decorate value } | |
define_method("#{key}!") { decorate! value } | |
end | |
private | |
def decorate(str) | |
"#{str}#{self}#{ABORT}" | |
end | |
def decorate!(str) | |
insert 0, str | |
self << ABORT | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment