Class: TNS::Color::RGB

Inherits:
Base
  • Object
show all
Defined in:
lib/tns/color/rgb.rb

Overview

RGB is our base representation for color objects.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(red = 0, green = 0, blue = 0) ⇒ RGB

Returns a new instance of RGB.



9
10
11
12
# File 'lib/tns/color/rgb.rb', line 9

def initialize(red = 0, green = 0, blue = 0)
  @red, @green, @blue = [red, green, blue].map { |color| normalize(color) }
  super()
end

Instance Attribute Details

#blueObject (readonly)

Returns the value of attribute blue.



7
8
9
# File 'lib/tns/color/rgb.rb', line 7

def blue
  @blue
end

#greenObject (readonly)

Returns the value of attribute green.



7
8
9
# File 'lib/tns/color/rgb.rb', line 7

def green
  @green
end

#redObject (readonly)

Returns the value of attribute red.



7
8
9
# File 'lib/tns/color/rgb.rb', line 7

def red
  @red
end

Class Method Details

.from_hex(color) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/tns/color/rgb.rb', line 14

def self.from_hex(color, &)
  hex = color.scan(/[0-9a-f]/i)
  case hex.size
  when 3
    new(*hex.map { |v| (v * 2).to_i(16) }, &)
  when 6
    new(*hex.each_slice(2).map { |v| v.join.to_i(16) }, &)
  else
    raise ArgumentError, "Invalid color #{color}. Please provide a color in hex format."
  end
end

Instance Method Details

#==(other) ⇒ Object



58
59
60
# File 'lib/tns/color/rgb.rb', line 58

def ==(other)
  other.class == self.class && other.state == state
end

#shade(step) ⇒ Object

Return a new instance of RGB that is shaded by step



35
36
37
38
39
40
# File 'lib/tns/color/rgb.rb', line 35

def shade(step)
  red = @red * (1 - (0.2 * step))
  green = @green * (1 - (0.2 * step))
  blue = @blue * (1 - (0.2 * step))
  Shade.new(RGB.new(red, green, blue), step)
end

#stateObject



62
63
64
# File 'lib/tns/color/rgb.rb', line 62

def state
  instance_variables.map { |variable| instance_variable_get variable }
end

#tint(step) ⇒ Object

Return a new instance of RGB that is tinted by step



27
28
29
30
31
32
# File 'lib/tns/color/rgb.rb', line 27

def tint(step)
  red = @red + ((255 - @red) * step * 0.2)
  green = @green + ((255 - @green) * step * 0.2)
  blue = @blue + ((255 - @blue) * step * 0.2)
  Tint.new(RGB.new(red, green, blue), step)
end

#to_cssObject



50
51
52
# File 'lib/tns/color/rgb.rb', line 50

def to_css
  "rgb(#{self})"
end

#to_hexObject



42
43
44
# File 'lib/tns/color/rgb.rb', line 42

def to_hex
  Hex.new(self)
end

#to_hslObject



46
47
48
# File 'lib/tns/color/rgb.rb', line 46

def to_hsl
  HSL.new(self)
end

#to_sObject



54
55
56
# File 'lib/tns/color/rgb.rb', line 54

def to_s
  format("%<red>d %<green>d %<blue>d", red: @red, green: @green, blue: @blue)
end