Class: ReggieB

Inherits:
Object
  • Object
show all
Defined in:
lib/reggieb.rb

Class Method Summary collapse

Class Method Details

.convert(s) ⇒ Object

converts rgb colors to hex colors and vice versa. The input is a string representing an rgb or hex color. Many formats are allowed, including:

  • “rgb(255, 255, 255)”

  • “rgb(255, 255, 255);”

  • “rgb 255, 255, 255 ”

  • “(255, 255, 255)”

  • “255, 255, 255”

  • “255 255 255”

  • “rgb(100%, 100%, 100%)”

  • “100% 100% 100%”

  • “0xffffff”

  • “0xFFFFFF”

  • “#ffffff”

  • “ffffff”

  • “fff”

In the case only three hex digits are given, the three digits are assumed to expand into six digits like so:

  • fff => ffffff

  • 78e => 7788ee

  • 084 => 008844

  • ace => aaccee

The output is either a hex color or an rgb color. A hex color is represented as a string formatted like “0xdddddd” where d represents a hex digit. An rgb color is represented as an array of three integers between 0 and 255.

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/reggieb.rb', line 32

def self.convert(s)
  s = s.downcase
  s.gsub!(';', '')
  if s =~ /^\s*((0x|#|)[0-9,a-f]{6})\s*$/
    return to_rgb($1)
  end
  if s =~ /^\s*(0x|#|)([0-9,a-f])([0-9,a-f])([0-9,a-f])\s*$/
    s = $2 + $2 + $3 + $3 + $4 + $4
    return to_rgb(s)
  end
  if s =~ /^\D*(\d{1,3})%\D*(\d{1,3})%\D*(\d{1,3})%\D*$/
    percent_to_byte = 255.0 / 100.0
    return to_hex($1.to_i*percent_to_byte, $2.to_i*percent_to_byte, $3.to_i*percent_to_byte)
  end
  if s =~ /^\D*(\d{1,3})\D+(\d{1,3})\D+(\d{1,3})\D*$/
    return to_hex($1.to_i, $2.to_i, $3.to_i)
  end
  raise ArgumentError.new("Bad color format.")
end

.to_hex(r, g, b) ⇒ Object

converts an rgb color to hex. rgb values must be between 0 and 255. The output is a string formatted like “0xdddddd” where d represents a hex digit.



55
56
57
58
59
60
61
62
63
64
# File 'lib/reggieb.rb', line 55

def self.to_hex(r, g, b)
  r = r.round
  g = g.round
  b = b.round
  unless (0..255).include?(r) && (0..255).include?(g) && (0..255).include?(b)
    message = "RGB values should be between 0 and 255.  Received #{r}, #{g}, #{b}."
    raise ArgumentError.new(message)
  end
  "0x#{to_hex_byte(r)}#{to_hex_byte(g)}#{to_hex_byte(b)}"
end

.to_rgb(hex) ⇒ Object

converts a hex color to rgb. The hex string should be formatted as “0xdddddd” or “dddddd” where d represents a hex digit. An array of three integers is returned representing red, green, and blue values between 0 and 255.



70
71
72
73
74
75
76
77
78
79
# File 'lib/reggieb.rb', line 70

def self.to_rgb(hex)
  hex = hex.downcase
  if hex !~ /0x[0-9,a-f]{6}/ && hex !~ /[0-9,a-f]{6}/
    raise ArgumentError.new("Hex number should be formatted as 0xdddddd or dddddd.")
  end
  last_byte   = hex[-2, 2]
  middle_byte = hex[-4, 2]
  first_byte  = hex[-6, 2]
  return [first_byte.to_i(16), middle_byte.to_i(16), last_byte.to_i(16)]
end