Class: Falu::Colors::HSL

Inherits:
Base
  • Object
show all
Defined in:
lib/falu/colors/hsl.rb

Instance Attribute Summary

Attributes inherited from Base

#color

Instance Method Summary collapse

Methods inherited from Base

#as_json

Constructor Details

#initialize(*color, hex: nil, rgb: nil) ⇒ HSL

Returns a new instance of HSL.



6
7
8
9
10
# File 'lib/falu/colors/hsl.rb', line 6

def initialize(*color, hex: nil, rgb: nil)
  color = color[0] if color.length == 1
  raise "Invalid HSL Color: #{color.to_s}" unless Falu::Color.hsl?(color)
  @color = color.is_a?(Array) ? color.join(',') : color
end

Instance Method Details

#colorsObject



12
13
14
# File 'lib/falu/colors/hsl.rb', line 12

def colors
  @colors ||= color.to_s.split(',').map { |c| c.strip.to_f }
end

#hueObject



16
17
18
# File 'lib/falu/colors/hsl.rb', line 16

def hue
  colors[0]
end

#hue_to_rgb(p, q, t) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/falu/colors/hsl.rb', line 40

def hue_to_rgb(p, q, t)
  t += 1.0 if t < 0
  t -= 1.0 if t > 1
  return p + (q - p) * 6.0 * t if t < (1.0/6.0)
  return q if t < (1.0/2.0)
  return p + (q - p) * (2.0/3.0 - t) * 6.0 if t < (2.0/3.0)
  return p
end

#lightnessObject



24
25
26
# File 'lib/falu/colors/hsl.rb', line 24

def lightness
  colors[2]
end

#saturationObject



20
21
22
# File 'lib/falu/colors/hsl.rb', line 20

def saturation
  colors[1]
end

#to_aObject



32
33
34
# File 'lib/falu/colors/hsl.rb', line 32

def to_a
  colors
end

#to_hObject



36
37
38
# File 'lib/falu/colors/hsl.rb', line 36

def to_h
  {hue: hue, saturation: saturation, lightness: lightness}
end

#to_hexObject



68
69
70
# File 'lib/falu/colors/hsl.rb', line 68

def to_hex
  to_rgb.to_hex
end

#to_hslObject



49
50
51
# File 'lib/falu/colors/hsl.rb', line 49

def to_hsl
  self
end

#to_rgbObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/falu/colors/hsl.rb', line 53

def to_rgb
  red = grn = blu = lit = (lightness.to_f / 100.0)
  hue, sat = (self.hue.to_f / 360.0), (saturation.to_f / 100.0)

  if sat > 0
    lum = lit < 0.5 ? lit * (1.0 + sat) : (lit + sat) - (lit * sat)
    crm = (2.0 * lit) - lum
    red = hue_to_rgb(crm, lum, hue + 1.0/3.0)
    grn = hue_to_rgb(crm, lum, hue)
    blu = hue_to_rgb(crm, lum, hue - 1.0/3.0)
  end

  Falu::Colors::RGB.new([(red * 255).round, (grn * 255).round, (blu * 255).round])
end

#to_sObject



28
29
30
# File 'lib/falu/colors/hsl.rb', line 28

def to_s
  colors.map { |c| c.round.to_s.rjust(3, '0') }.join(',')
end