Class: LuminosityContrast::Color

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Color

Returns a new instance of Color.



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

def initialize(*args)
  input = args.size == 1 ? args[0] : args
  @r, @g, @b = Color.rgb_from(input)
end

Instance Attribute Details

#bObject (readonly)

Returns the value of attribute b.



3
4
5
# File 'lib/luminosity_contrast/color.rb', line 3

def b
  @b
end

#gObject (readonly)

Returns the value of attribute g.



3
4
5
# File 'lib/luminosity_contrast/color.rb', line 3

def g
  @g
end

#rObject (readonly)

Returns the value of attribute r.



3
4
5
# File 'lib/luminosity_contrast/color.rb', line 3

def r
  @r
end

Class Method Details

.rgb_from(input) ⇒ Object

expects a 3 or 6 character hex color code or an array with 3 numbers between 0 and 255 or an object that responds to .r, .g, .b



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/luminosity_contrast/color.rb', line 27

def rgb_from(input)
  case input
  when String # hex code
    raise 'Invalid hex code' unless input =~ /\A([0-9a-f]{3}){1,2}\z/i
    rgb = if input.size == 3
      input.split('').map { |h| h * 2 }
    else
      input.scan(/.{2}/)
    end
    rgb.map { |h| h.hex.to_i }
  when Array # array of numbers
    raise 'Invalid RGB array' unless input.size == 3
    input.map(&:to_f)
  when Hash
    rgb = input.values_at(:r, :g, :b)
    raise 'Invalid RGB hash' unless rgb.size == 3
    rgb.map(&:to_f)
  else
    methods = [:r,:g, :b]
    if methods.select { |m| input.respond_to?(m) }.size == methods.size
      methods.map { |m| input.send(m) }
    else
      raise 'Invalid input'
    end
  end
end

Instance Method Details

#ratio(color) ⇒ Object



14
15
16
# File 'lib/luminosity_contrast/color.rb', line 14

def ratio(color)
  LuminosityContrast.ratio(self, color)
end

#relative_luminanceObject



10
11
12
# File 'lib/luminosity_contrast/color.rb', line 10

def relative_luminance
  LuminosityContrast.relative_luminance(r,g,b)
end

#to_rgbObject



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

def to_rgb
  [r, g, b]
end