Class: ColourConverter

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

Overview

We have a large number of pre-calculated colours Unfortunately the lightness method in SASS doesn’t take into account human eye sensitivity, and claims #ffff00 is 50% bright This tool uses w3c recommendations to calculate whether white or black text has better contrast for a given colour. www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests

Defined Under Namespace

Classes: ColourChanel

Constant Summary collapse

HEX =
/#([0-f]{2})([0-f]{2})([0-f]{2})/
RED_MULTIPLIER =
0.2126
GREEN_MULTIPLIER =
0.7152
BLUE_MULTIPLIER =
0.0722

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hex) ⇒ ColourConverter

Returns a new instance of ColourConverter.



37
38
39
40
41
42
43
# File 'lib/colour_helper.rb', line 37

def initialize(hex)
  @hex = hex
  matched = HEX.match(hex)
  @red = ColourChanel.new(matched[1])
  @green = ColourChanel.new(matched[2])
  @blue = ColourChanel.new(matched[3])
end

Instance Attribute Details

#hexObject (readonly)

Returns the value of attribute hex.



16
17
18
# File 'lib/colour_helper.rb', line 16

def hex
  @hex
end

Class Method Details

.blackObject



22
23
24
# File 'lib/colour_helper.rb', line 22

def self.black
  ColourConverter.new('#000000')
end

.whiteObject



18
19
20
# File 'lib/colour_helper.rb', line 18

def self.white
  ColourConverter.new('#ffffff')
end

Instance Method Details

#black_or_whiteObject



59
60
61
# File 'lib/colour_helper.rb', line 59

def black_or_white
  highest_contrast_ratio(ColourConverter.white, ColourConverter.black).hex
end

#contrast_ratio(other) ⇒ Object



50
51
52
53
# File 'lib/colour_helper.rb', line 50

def contrast_ratio(other)
  darker, lighter = [self, other].sort_by(&:luminance)
  (lighter.luminance + 0.05) / (darker.luminance + 0.05)
end

#highest_contrast_ratio(*candidates) ⇒ Object



55
56
57
# File 'lib/colour_helper.rb', line 55

def highest_contrast_ratio(*candidates)
  candidates.max_by { |candidate| contrast_ratio(candidate) }
end

#luminanceObject



45
46
47
48
# File 'lib/colour_helper.rb', line 45

def luminance
  @luminance ||=
    (RED_MULTIPLIER * @red.luminance) + (GREEN_MULTIPLIER * @green.luminance) + (BLUE_MULTIPLIER * @blue.luminance)
end