class String
Colorize String class extension.
def color_matrix( txt = "[X]" )
Display color matrix with color names.
def color_matrix( txt = "[X]" ) size = String.colors.length String.colors.each do | color | String.colors.each do | back | print txt.colorize( :color => color, :background => back ) end puts " < #{color}" end String.colors.reverse.each_with_index do | back, index | puts "#{"|".rjust(txt.length)*(size-index)} < #{back}" end end
def colorize( params )
puts "This is blue text on red".blue.on_red.blink
puts "This is red on blue and underline".colorize( :red ).on_blue.underline
puts "This is red on blue".colorize( :red ).on_blue
puts "This is blue text on red".blue.on_red
puts "This is blue with red background".colorize( :light_blue ).colorize( :background => :red )
puts "This is blue with red background".colorize( :color => :light_blue, :background => :red )
puts "This is also blue".colorize( :color => :blue )
puts "This is light blue".colorize( :light_blue )
puts "This is blue".colorize( :blue )
Examples:
Change color of string
def colorize( params ) return self unless STDOUT.isatty begin require 'Win32/Console/ANSI' if PLATFORM =~ /win32/ rescue LoadError raise 'You must gem install win32console to use color on Windows' end color_parameters = {} if (params.instance_of?(Hash)) color_parameters[:color] = COLORS[params[:color]] color_parameters[:background] = COLORS[params[:background]] color_parameters[:mode] = MODES[params[:mode]] elsif (params.instance_of?(Symbol)) color_parameters[:color] = COLORS[params] end color_parameters[:color] ||= @color || 9 color_parameters[:background] ||= @background || 9 color_parameters[:mode] ||= @mode || 0 color_parameters[:uncolorized] ||= @uncolorized || self.dup # calculate bright mode color_parameters[:color] += 50 if color_parameters[:color] > 10 color_parameters[:background] += 50 if color_parameters[:background] > 10 return "\033[#{color_parameters[:mode]};#{color_parameters[:color]+30};#{color_parameters[:background]+40}m#{color_parameters[:uncolorized]}\033[0m".set_color_parameters( color_parameters ) end
def colorized?
Return true if sting is colorized
def colorized? return !@uncolorized.nil? end
def colors
Return array of available colors used by colorize method
def colors keys = [] COLORS.each_key do | key | keys << key end keys end
def modes
Return array of available modes used by colorize method
def modes keys = [] MODES.each_key do | key | keys << key end keys end
def set_color_parameters( params )
Set color values in new string intance
def set_color_parameters( params ) if (params.instance_of?(Hash)) @color = params[:color] @background = params[:background] @mode = params[:mode] @uncolorized = params[:uncolorized] self else nil end end
def uncolorize
Return uncolorized string
def uncolorize return @uncolorized || self end