From f3bc7f8ebaf614a681664eea1e9bccfe81621368 Mon Sep 17 00:00:00 2001 From: Max Aller Date: Sun, 4 Jan 2009 00:24:13 -0800 Subject: [PATCH] Fix up set_default to not munge existing values. --- lib/couchrest/core/model.rb | 3 ++- spec/couchrest/core/model_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/couchrest/core/model.rb b/lib/couchrest/core/model.rb index a1c329b..2d5207a 100644 --- a/lib/couchrest/core/model.rb +++ b/lib/couchrest/core/model.rb @@ -506,9 +506,10 @@ module CouchRest private def apply_defaults + return unless new_document? if self.class.default self.class.default.each do |k,v| - self[k] = v + self[k] = v unless self.key?(k.to_s) end end end diff --git a/spec/couchrest/core/model_spec.rb b/spec/couchrest/core/model_spec.rb index 55b5a0e..e15de5a 100644 --- a/spec/couchrest/core/model_spec.rb +++ b/spec/couchrest/core/model_spec.rb @@ -22,6 +22,7 @@ class WithTemplateAndUniqueID < CouchRest::Model 'more-template' => [1,2,3] }) key_accessor :preset + key_accessor :has_no_default end class Question < CouchRest::Model @@ -222,10 +223,31 @@ describe CouchRest::Model do describe "a model with template values" do before(:all) do @tmpl = WithTemplateAndUniqueID.new + @tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'important-field' => '1') end it "should have fields set when new" do @tmpl.preset.should == 'value' end + it "shouldn't override explicitly set values" do + @tmpl2.preset.should == 'not_value' + end + it "shouldn't override existing documents" do + @tmpl2.save + tmpl2_reloaded = WithTemplateAndUniqueID.get(@tmpl2.id) + @tmpl2.preset.should == 'not_value' + tmpl2_reloaded.preset.should == 'not_value' + end + it "shouldn't fill in existing documents" do + @tmpl2.save + # If user adds a new default value, shouldn't be retroactively applied to + # documents upon fetching + WithTemplateAndUniqueID.set_default({:has_no_default => 'giraffe'}) + + tmpl2_reloaded = WithTemplateAndUniqueID.get(@tmpl2.id) + @tmpl2.has_no_default.should be_nil + tmpl2_reloaded.has_no_default.should be_nil + WithTemplateAndUniqueID.new.has_no_default.should == 'giraffe' + end end describe "getting a model" do