Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,13 @@ def initialize(name, content = nil)
#
# @return [Tree::TreeNode] A copy of this node.
def detached_copy
self.class.new(@name, @content ? @content.clone : nil)
cloned_content =
begin
@content && @content.clone
rescue TypeError
@content
end
self.class.new(@name, cloned_content)
end

# Returns a copy of entire (sub-)tree from this node.
Expand Down
58 changes: 58 additions & 0 deletions spec/tree_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,62 @@

it_behaves_like "any detached node"
end

shared_examples_for "any cloned node" do
it "is equal to the original" do
expect(@clone).to eq @tree
end
it "is not identical to the original" do
expect(clone).not_to be @tree
end
end

context "#detached_copy", "without content" do
before(:each) do
@tree = Tree::TreeNode.new("A", nil)
@clone = @tree.detached_copy
end

it_behaves_like "any cloned node"
end

context "#detached_copy", "with clonable content" do
before(:each) do
@tree = Tree::TreeNode.new("A", "clonable content")
@clone = @tree.detached_copy
end

it "makes a clone of the content" do
expect(@clone.content).to eq @tree.content
expect(@clone.content).not_to be @tree.content
end

it_behaves_like "any cloned node"
end

context "#detached_copy", "with unclonable content" do
before(:each) do
@tree = Tree::TreeNode.new("A", :unclonable_content)
@clone = @tree.detached_copy
end

it "keeps the content" do
expect(@clone.content).to be @tree.content
end

it_behaves_like "any cloned node"
end

context "#detached_copy", "with false as content" do
before(:each) do
@tree = Tree::TreeNode.new("A", false)
@clone = @tree.detached_copy
end

it "keeps the content" do
expect(@clone.content).to be @tree.content
end

it_behaves_like "any cloned node"
end
end