diff --git a/lib/virtus/attribute/default_value.rb b/lib/virtus/attribute/default_value.rb index 4697b112..2d845931 100644 --- a/lib/virtus/attribute/default_value.rb +++ b/lib/virtus/attribute/default_value.rb @@ -29,8 +29,7 @@ class DefaultValue # # @api private def initialize(attribute, value) - @attribute = attribute - @value = case value when *DUP_CLASSES then value else value.dup end + @attribute, @value = attribute, value end # Evaluates the value @@ -41,7 +40,13 @@ def initialize(attribute, value) # # @api private def evaluate(instance) - callable? ? call(instance) : value + if callable? + call(instance) + elsif duplicable? + value.dup + else + value + end end private @@ -66,6 +71,15 @@ def callable? value.respond_to?(:call) end + # Returns whether or not the value is duplicable + # + # # return [TrueClass, FalseClass] + # + # @api private + def duplicable? + case value when *DUP_CLASSES then false else true end + end + end # class DefaultValue end # class Attribute end # module Virtus diff --git a/spec/unit/virtus/attribute/default_value/class_methods/new_spec.rb b/spec/unit/virtus/attribute/default_value/class_methods/new_spec.rb index 8a4ff443..fcabde64 100644 --- a/spec/unit/virtus/attribute/default_value/class_methods/new_spec.rb +++ b/spec/unit/virtus/attribute/default_value/class_methods/new_spec.rb @@ -5,18 +5,15 @@ let(:attribute) { Virtus::Attribute::String.new(:attribute) } - context 'with a value that can be duped' do + context 'with a duplicable value' do let(:value) { 'something' } - - its(:value) { should eql(value) } - its(:value) { should_not equal(value) } + its(:value) { should equal(value) } end - context 'with a value that cannot be duped' do + context 'with a non-duplicable value' do [ nil, true, false, 1, :symbol ].each do |value| context "with #{value.inspect}" do let(:value) { value } - its(:value) { should equal(value) } end end diff --git a/spec/unit/virtus/attribute/default_value/instance_methods/evaluate_spec.rb b/spec/unit/virtus/attribute/default_value/instance_methods/evaluate_spec.rb index 98f0a13f..8a8b8733 100644 --- a/spec/unit/virtus/attribute/default_value/instance_methods/evaluate_spec.rb +++ b/spec/unit/virtus/attribute/default_value/instance_methods/evaluate_spec.rb @@ -8,8 +8,16 @@ let(:instance) { Class.new } context 'with a non-callable value' do - let(:value) { 'something' } - it { should eql(value) } + context 'with a non-duplicable value' do + let(:value) { nil } + it { should eql(value) } + end + + context 'with a duplicable value' do + let(:value) { 'something' } + it { should eql(value) } + it { should_not equal(value)} + end end context 'with a callable value' do