Class: Rainbow::Color

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

Direct Known Subclasses

Indexed

Defined Under Namespace

Classes: Indexed, Named, RGB, X11Named

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#groundObject (readonly)

Returns the value of attribute ground.



5
6
7
# File 'lib/rainbow/color.rb', line 5

def ground
  @ground
end

Class Method Details

.build(ground, values) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rainbow/color.rb', line 7

def self.build(ground, values)
  unless [1, 3].include?(values.size)
    raise ArgumentError,
          "Wrong number of arguments for color definition, should be 1 or 3"
  end

  color = values.size == 1 ? values.first : values

  case color
  # NOTE: Properly handle versions before/after Ruby 2.4.0.
  # Ruby 2.4+ unifies Fixnum & Bignum into Integer.
  # However previous versions would still use Fixnum.
  # To avoid missing `Fixnum` input, call `0.class` which would
  # return either `Integer` or `Fixnum`.
  when 0.class
    Indexed.new(ground, color)
  when Symbol
    if Named.color_names.include?(color)
      Named.new(ground, color)
    elsif X11Named.color_names.include?(color)
      X11Named.new(ground, color)
    else
      raise ArgumentError,
            "Unknown color name, valid names: " +
            (Named.color_names + X11Named.color_names).join(', ')
    end
  when Array
    RGB.new(ground, *color)
  when String
    RGB.new(ground, *parse_hex_color(color))
  end
end

.parse_hex_color(hex) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rainbow/color.rb', line 40

def self.parse_hex_color(hex)
  unless hex =~ /^#?[a-f0-9]{6}/i
    raise ArgumentError,
          "Invalid hexadecimal RGB triplet. Valid format: /^#?[a-f0-9]{6}/i"
  end

  hex = hex.sub(/^#/, '')
  r   = hex[0..1].to_i(16)
  g   = hex[2..3].to_i(16)
  b   = hex[4..5].to_i(16)

  [r, g, b]
end