Skip to content

Commit

Permalink
Dup default value on evaluate rather than on initialization
Browse files Browse the repository at this point in the history
Issue #25
  • Loading branch information
Ryan Closner committed Nov 16, 2011
1 parent 9568cc4 commit 056ee56
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
20 changes: 17 additions & 3 deletions lib/virtus/attribute/default_value.rb
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Up @@ -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
Expand Down
Expand Up @@ -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
Expand Down

0 comments on commit 056ee56

Please sign in to comment.