Class: ColorConverters::HexConverter

Inherits:
BaseConverter show all
Defined in:
lib/color_converters/converters/hex_converter.rb

Constant Summary

Constants inherited from BaseConverter

BaseConverter::IMPORT_DP, BaseConverter::OUTPUT_DP

Instance Attribute Summary

Attributes inherited from BaseConverter

#original_value, #rgba

Class Method Summary collapse

Methods inherited from BaseConverter

#alpha, #cielab, #cielch, #cmyk, factory, #hex, #hsb, #hsl, #hsv, inherited, #initialize, #name, #oklab, #oklch, #rgb, #xyz

Constructor Details

This class inherits a constructor from ColorConverters::BaseConverter

Class Method Details

.hex_to_rgba(hex_input) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/color_converters/converters/hex_converter.rb', line 26

def self.hex_to_rgba(hex_input)
  hex_input = self.normalize_hex(hex_input)

  r = hex_input[0, 2].hex
  g = hex_input[2, 2].hex
  b = hex_input[4, 2].hex
  a = hex_input.length == 8 ? hex[6, 2].hex : 1.0

  [r, g, b, a]
end

.matches?(colour) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
8
9
# File 'lib/color_converters/converters/hex_converter.rb', line 5

def self.matches?(colour)
  return false unless colour.is_a?(String)

  colour.include?('#') && [4, 7, 9].include?(colour.length)
end

.normalize_hex(hex_input) ⇒ Object



43
44
45
46
47
# File 'lib/color_converters/converters/hex_converter.rb', line 43

def self.normalize_hex(hex_input)
  hex_input = hex_input.gsub('#', '')

  (hex_input.length == 3 ? hex_input[0, 1] * 2 + hex_input[1, 1] * 2 + hex_input[2, 1] * 2 : hex_input).downcase
end

.rgb_to_hex(rgb_array) ⇒ Object



37
38
39
40
41
# File 'lib/color_converters/converters/hex_converter.rb', line 37

def self.rgb_to_hex(rgb_array)
  r, g, b = rgb_array

  format('#%<r>02x%<g>02x%<b>02x', r: r, g: g, b: b)
end