Class: Smplkit::Management::Color

Inherits:
Object
  • Object
show all
Defined in:
lib/smplkit/management/types.rb

Overview

A color, expressed as a CSS hex string.

Smplkit::Color.new("#ef4444")        # 6-digit hex
Smplkit::Color.new("#fff")           # 3-digit shorthand
Smplkit::Color.new("#ef4444aa")      # 8-digit with alpha
Smplkit::Color.rgb(239, 68, 68)      # RGB components

Frozen — construct a fresh Color to change a value.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hex) ⇒ Color

Returns a new instance of Color.

Raises:

  • (TypeError)


31
32
33
34
35
36
37
38
39
40
# File 'lib/smplkit/management/types.rb', line 31

def initialize(hex)
  raise TypeError, "Color hex must be a String, got #{hex.class}: #{hex.inspect}" unless hex.is_a?(String)
  unless HEX_RE.match?(hex)
    raise ArgumentError,
          "Invalid color #{hex.inspect}: must be a CSS hex string like '#RGB', '#RRGGBB', or '#RRGGBBAA'"
  end

  @hex = hex.downcase.freeze
  freeze
end

Instance Attribute Details

#hexObject (readonly)

Returns the value of attribute hex.



29
30
31
# File 'lib/smplkit/management/types.rb', line 29

def hex
  @hex
end

Class Method Details

.rgb(red, green, blue) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/smplkit/management/types.rb', line 42

def self.rgb(red, green, blue)
  [%w[red green blue], [red, green, blue]].transpose.each do |name, val|
    unless val.is_a?(Integer) && !val.is_a?(TrueClass) && !val.is_a?(FalseClass)
      raise TypeError,
            "Color.rgb #{name} must be an Integer, got #{val.class}"
    end
    raise ArgumentError, "Color.rgb #{name} must be in range 0-255, got #{val.inspect}" unless val.between?(0,
                                                                                                            255)
  end

  new("##{red.to_s(16).rjust(2, "0")}#{green.to_s(16).rjust(2, "0")}#{blue.to_s(16).rjust(2, "0")}")
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



57
# File 'lib/smplkit/management/types.rb', line 57

def ==(other) = other.is_a?(Color) && other.hex == @hex

#hashObject



59
# File 'lib/smplkit/management/types.rb', line 59

def hash = @hex.hash

#to_sObject



55
# File 'lib/smplkit/management/types.rb', line 55

def to_s = @hex

#to_strObject



56
# File 'lib/smplkit/management/types.rb', line 56

def to_str = @hex