Module: SimpleColor::RGB::Parsers
- Included in:
- SimpleColor::RGB
- Defined in:
- lib/simplecolor/rgb.rb
Instance Method Summary collapse
- #parse(col, color_names: proc {|c| find_color(c)}) ⇒ Object
-
#rgb_hex(string) ⇒ Object
Creates RGB color from a HTML-like color definition string.
Instance Method Details
#parse(col, color_names: proc {|c| find_color(c)}) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# 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) ⇒ Object
Creates RGB color from a HTML-like color definition string
17 18 19 20 21 22 23 24 25 26 |
# 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 |