From 6118b66ec77b3110da5ed2e87f80d3e962c5066d Mon Sep 17 00:00:00 2001 From: Sam Pohlenz Date: Sat, 21 Dec 2024 15:02:58 +1030 Subject: [PATCH] Implement deep cloning of Configuration options (#532) --- lib/trestle/configurable.rb | 4 ++++ spec/trestle/configurable_spec.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/trestle/configurable.rb b/lib/trestle/configurable.rb index 0f9ae3c4..dc707e6a 100644 --- a/lib/trestle/configurable.rb +++ b/lib/trestle/configurable.rb @@ -40,6 +40,10 @@ def as_json(options=nil) end end + def initialize_copy(original) + @options = original.options.deep_dup + end + def inspect "#<#{self.class.name || "Anonymous(Trestle::Configurable)"}>" end diff --git a/spec/trestle/configurable_spec.rb b/spec/trestle/configurable_spec.rb index 90d3d784..4bc580ea 100644 --- a/spec/trestle/configurable_spec.rb +++ b/spec/trestle/configurable_spec.rb @@ -52,6 +52,26 @@ end end + describe "#dup" do + let(:original_options) { config.options } + let(:duplicate) { config.dup } + + it "returns a new instance with a clone of the options" do + expect(duplicate.options).to eq(original_options) + expect(duplicate.options).not_to be(original_options) + end + end + + describe "#clone" do + let(:original_options) { config.options } + let(:duplicate) { config.clone } + + it "returns a new instance with a clone of the options" do + expect(duplicate.options).to eq(original_options) + expect(duplicate.options).not_to be(original_options) + end + end + describe ".option" do it "defines accessors for the option" do configurable.option :myoption @@ -112,5 +132,15 @@ config.first.second.third = "value" expect(config.as_json({})).to eq({ first: { second: { third: "value" } } }) end + + describe "#dup" do + it "creates clones of nested options" do + config.first.second.third = "value" + duplicate = config.dup + + expect(duplicate.second.options).to eq(config.second.options) + expect(duplicate.second.options).not_to be(config.second.options) + end + end end end