Skip to content

Commit

Permalink
Merge pull request #83 from chiting/add-hex-check
Browse files Browse the repository at this point in the history
Add hexadecimal RGB triplet string format check
  • Loading branch information
ku1ik authored Jul 8, 2018
2 parents 21b18bc + c7cb8da commit 4bba7e3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/rainbow/color.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def self.build(ground, values)
end

def self.parse_hex_color(hex)
unless hex =~ /^#?[a-f0-9]{6}/i
raise ArgumentError,
"Invalid hexadecimal RGB triplet. Valid format: /^#?[a-f0-9]{6}/i"
end

hex = hex.sub(/^#/, '')
r = hex[0..1].to_i(16)
g = hex[2..3].to_i(16)
Expand Down
10 changes: 9 additions & 1 deletion spec/unit/color_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ module Rainbow
specify { expect(subject.b).to eq(112) }
end

context "when single string given" do
context "when single hexadecimal string given" do
let(:values) { ['#deadcc'] }

it { should be_instance_of(Color::RGB) }
Expand All @@ -48,6 +48,14 @@ module Rainbow
specify { expect(subject.b).to eq(204) }
end

context "when single non hexadecimal string given" do
let(:values) { ['green'] }

it 'raises ArgumentError' do
expect { subject }.to raise_error(ArgumentError)
end
end

context "when 2 elements" do
let(:values) { [1, 2] }

Expand Down

0 comments on commit 4bba7e3

Please sign in to comment.