Skip to content

Commit 3d88a81

Browse files
committed
implement Ferrum::RGBA class
1 parent d463abc commit 3d88a81

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

lib/ferrum/rbga.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
module Ferrum
2+
class RGBA
3+
def initialize(red, green, blue, alpha)
4+
self.red = red
5+
self.green = green
6+
self.blue = blue
7+
self.alpha = alpha
8+
9+
validate
10+
end
11+
12+
def to_h
13+
{ r: red, g: green, b: blue, a: alpha }
14+
end
15+
16+
private
17+
18+
attr_accessor :red, :green, :blue, :alpha
19+
20+
def validate
21+
[red, green, blue].each(&method(:validate_color))
22+
validate_alpha
23+
end
24+
25+
def validate_color(value)
26+
return if value && value.is_a?(Integer) && Range.new(0, 255).include?(value)
27+
28+
raise ArgumentError, "Wrong value of #{value} should be Integer from 0 to 255"
29+
end
30+
31+
def validate_alpha
32+
return if alpha && alpha.is_a?(Float) && Range.new(0.0, 1.0).include?(alpha)
33+
34+
raise ArgumentError,
35+
"Wrong alpha value #{alpha} should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)"
36+
end
37+
end
38+
end

spec/rbga_spec.rb

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# frozen_string_literal: true
2+
3+
require "ferrum/rbga"
4+
5+
module Ferrum
6+
describe RGBA do
7+
describe '#to_h' do
8+
it { expect(RGBA.new(0, 0, 0, 0.0).to_h).to eq({ r: 0, g: 0, b: 0, a: 0.0 }) }
9+
it { expect(RGBA.new(255, 255, 255, 1.0).to_h).to eq({ r: 255, g: 255, b: 255, a: 1.0 }) }
10+
end
11+
12+
it 'raises ArgumentError for not Float value of alpha' do
13+
expect {
14+
RGBA.new(0, 0, 0, 0)
15+
}.to raise_exception(
16+
ArgumentError,
17+
'Wrong alpha value 0 should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)')
18+
end
19+
20+
it 'raises ArgumentError wrong value of alpha' do
21+
expect {
22+
RGBA.new(0, 0, 0, 2.0)
23+
}.to raise_exception(
24+
ArgumentError,
25+
'Wrong alpha value 2.0 should be Float between 0.0 (fully transparent) and 1.0 (fully opaque)')
26+
end
27+
28+
it 'raises ArgumentError for wrong value of red' do
29+
expect {
30+
RGBA.new(-1, 0, 0, 0.0)
31+
}.to raise_exception(ArgumentError, 'Wrong value of -1 should be Integer from 0 to 255')
32+
end
33+
34+
it 'raises ArgumentError for wrong value of green' do
35+
expect {
36+
RGBA.new(0, 256, 0, 0.0)
37+
}.to raise_exception(ArgumentError, 'Wrong value of 256 should be Integer from 0 to 255')
38+
end
39+
40+
it 'raises ArgumentError for wrong value of blue' do
41+
expect {
42+
RGBA.new(0, 0, 0.0, 0.0)
43+
}.to raise_exception(ArgumentError, 'Wrong value of 0.0 should be Integer from 0 to 255')
44+
end
45+
end
46+
end

0 commit comments

Comments
 (0)