module SimpleColor::RGB::Parsers
Public Instance Methods
parse(col, color_names: proc {|c| find_color(c)})
click to toggle source
# File lib/simplecolor/rgb.rb, line 28 def parse(col, color_names: proc {|c| find_color(c)}) case col when self return col when Proc scol=col.call(self) return parse(scol, color_names: color_names) when Symbol if ANSI_COLORS_16.key?(col) return self.new(col, mode: 16) end when Array return self.new(col, mode: true) when String if (m=col.match(/\A(?:rgb)?256[+:-]?(?<grey>gr[ae]y)?(?<red>\d+)(?:[+:-](?<green>\d+)[+:-](?<blue>\d+))?\z/)) grey=m[:grey]; red=m[:red]&.to_i; green=m[:green]&.to_i; blue=m[:blue]&.to_i if grey return self.new(GREY256+red, mode: 256) elsif green and blue return self.new([red, green, blue], mode: 256) else raise WrongRGBColor.new(col) if green return self.new(red, mode: 256) end elsif (m=col.match(/\A(?:rgb[+:-]?)?(?<red>\d+)[+:-](?<green>\d+)[+:-](?<blue>\d+)\z/)) red=m[:red]&.to_i; green=m[:green]&.to_i; blue=m[:blue]&.to_i return self.new([red, green, blue], mode: :truecolor) elsif (m=col.match(/\A#?(?<hex_color>[[:xdigit:]]{3}{1,2})\z/)) # 3 or 6 hex chars return self.new(rgb_hex(m[:hex_color]), mode: :truecolor) end end if color_names && (c=color_names[col]) return self.parse(c, color_names: nil) else # fallback to parsing col.to_s? raise WrongRGBColor.new(col) end end
rgb_hex(string)
click to toggle source
Creates RGB
color from a HTML-like color definition string
# File lib/simplecolor/rgb.rb, line 17 def rgb_hex(string) case string.size when 6 string.each_char.each_slice(2).map{ |hex_color| hex_color.join.to_i(16) } when 3 string.each_char.map{ |hex_color_half| (hex_color_half*2).to_i(16) } else raise WrongRGBColor.new(string) end end