Skip to content
Browse files

Merge pull request #39 from rclosner/duplicable

Dup default value on evaluate rather than on initialization
  • Loading branch information...
2 parents 9568cc4 + 056ee56 commit a5a003d2f54623b61a60c041d5a22d2e5a419c5d @solnic committed Nov 16, 2011
View
20 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
View
9 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
View
12 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

0 comments on commit a5a003d

Please sign in to comment.
Something went wrong with that request. Please try again.