Permalink
Browse files

Merge pull request #87 from senny/topic/value_object_copies

ValueObject should not be duplicated
  • Loading branch information...
2 parents 1fd6db7 + 0402b3e commit 85741a39b9d03d6c9fe22b204efb6e691db740f2 @dkubb dkubb committed May 17, 2012
View
@@ -33,5 +33,6 @@ measurements
## BUNDLER
.bundle
Gemfile.lock
+bin/
## PROJECT::SPECIFIC
View
@@ -53,6 +53,16 @@ def initialize(attributes = {})
def with(attribute_updates)
self.class.new(get_attributes(&FILTER_NONE).merge(attribute_updates))
end
+
+ # ValueObjects are immutable and can't be cloned. They always represent the same value.
+ #
+ # @return [self]
+ #
+ # @api public
+ def clone
+ self
+ end
+ alias dup clone
end
module ClassMethods
@@ -4,6 +4,13 @@
before do
module Examples
+
+ class Reference
+ include Virtus::ValueObject
+
+ attribute :ref, String
+ end
+
class Page
include Virtus
@@ -12,6 +19,7 @@ class Page
attribute :view_count, Integer, :default => 0
attribute :published, Boolean, :default => false, :accessor => :private
attribute :editor_title, String, :default => :default_editor_title
+ attribute :reference, String, :default => Reference.new
def default_editor_title
published? ? title : "UNPUBLISHED: #{title}"
@@ -41,4 +49,12 @@ def default_editor_title
subject.editor_title.should == 'UNPUBLISHED: Top Secret'
end
+ context 'with a ValueObject' do
+ it 'should not duplicate the ValueObject' do
+ page1 = Examples::Page.new
+ page2 = Examples::Page.new
+ page1.reference.should equal(page2.reference)
+ end
+ end
+
end
@@ -0,0 +1,22 @@
+require 'spec_helper'
+
+describe Virtus::ValueObject::InstanceMethods, 'duplication' do
+ let(:described_class) do
+ Class.new do
+ include Virtus::ValueObject
+
+ attribute :name, String
+ end
+ end
+
+ subject { described_class.new }
+
+ it '#clone returns the same instance' do
+ subject.should equal(subject.clone)
+ end
+
+ it '#dup returns the same instance' do
+ subject.should equal(subject.dup)
+ end
+
+end

0 comments on commit 85741a3

Please sign in to comment.