From 3ef35cdf4fd699cce93a51b1167d765324a213bd Mon Sep 17 00:00:00 2001 From: Mario Visic Date: Thu, 27 Dec 2018 21:30:58 +0800 Subject: Allow color to initialize from an existing color object Setting a 2d object's color to be random is great, however it's difficult to re-use that color without manually extracting out the rgba values from that color object. Ideally it would be convenient to be able to do this: ```ruby square = Square.new(color: 'random') square_two = Square.new(color: square.color) ``` This patch allows this behavior from any 2d shape, making it much easier to reuse those random colors :) --- lib/ruby2d/color.rb | 3 +++ test/color_spec.rb | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/ruby2d/color.rb b/lib/ruby2d/color.rb index be223d3..8b72dbb 100644 --- a/lib/ruby2d/color.rb +++ b/lib/ruby2d/color.rb @@ -66,6 +66,8 @@ module Ruby2D end when Array @r, @g, @b, @a = [c[0], c[1], c[2], c[3]] + when Color + @r, @g, @b, @a = [c.r, c.g, c.b, c.a] end end end @@ -90,6 +92,7 @@ module Ruby2D # Check if the color is valid def self.is_valid?(c) + c.is_a?(Color) || # color object @@colors.key?(c) || # keyword self.is_hex?(c) || # hexadecimal value diff --git a/test/color_spec.rb b/test/color_spec.rb index 4f0ec35..e22c2c5 100644 --- a/test/color_spec.rb +++ b/test/color_spec.rb @@ -24,6 +24,17 @@ RSpec.describe Ruby2D::Color do it "raises error on bad color" do expect { Ruby2D::Color.new 42 }.to raise_error Ruby2D::Error end + + it "accepts an existing color object" do + expect { Ruby2D::Color.new(Ruby2D::Color.new('red')) }.to_not raise_error Ruby2D::Error + end + + it "assigns rgba from an existing color" do + c1 = Ruby2D::Color.new([20, 60, 80, 100]) + c2 = Ruby2D::Color.new(c1) + + expect([c2.r, c2.g, c2.b, c2.a]).to eq([20, 60, 80, 100]) + end end describe "#opacity" do -- cgit v1.2.3