From 9399b27f3f58c1e333b6dd5f20bbcd3531fa4b5e Mon Sep 17 00:00:00 2001 From: Vinicius Teles Date: Fri, 7 Nov 2008 10:36:38 -0200 Subject: [PATCH] Added the method update_attributes_without_saving. To understand the reason, say you have this: class Post < CouchRest::Model key_accessor :title, :body, :author, comments cast :author, :as => 'Author' cast :comments, :as => ['Comment'] end comment = post.comments.first I'd like to do comment.update_attributes_without_saving hash because otherwise, it would create a new document for comment, which I don't want in my particular use. I just want to update the internal comment in the post. --- lib/couchrest/core/model.rb | 13 ++++++++++--- spec/couchrest/core/model_spec.rb | 12 ++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/couchrest/core/model.rb b/lib/couchrest/core/model.rb index 3aed10ac..89e118ca 100644 --- a/lib/couchrest/core/model.rb +++ b/lib/couchrest/core/model.rb @@ -456,15 +456,22 @@ def rev end # Takes a hash as argument, and applies the values by using writer methods - # for each key. Raises a NoMethodError if the corresponding methods are - # missing. In case of error, no attributes are changed. - def update_attributes hash + # for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are + # missing. In case of error, no attributes are changed. + def update_attributes_without_saving hash hash.each do |k, v| raise NoMethodError, "#{k}= method not available, use key_accessor or key_writer :#{k}" unless self.respond_to?("#{k}=") end hash.each do |k, v| self.send("#{k}=",v) end + end + + # Takes a hash as argument, and applies the values by using writer methods + # for each key. Raises a NoMethodError if the corresponding methods are + # missing. In case of error, no attributes are changed. + def update_attributes hash + update_attributes_without_saving hash save end diff --git a/spec/couchrest/core/model_spec.rb b/spec/couchrest/core/model_spec.rb index d350335a..e5cc1845 100644 --- a/spec/couchrest/core/model_spec.rb +++ b/spec/couchrest/core/model_spec.rb @@ -134,7 +134,7 @@ def generate_slug_from_title end end - describe "update attributes" do + describe "update attributes without saving" do before(:each) do a = Article.get "big-bad-danger" rescue nil a.destroy if a @@ -160,13 +160,21 @@ def generate_slug_from_title @art['title'].should == "big bad danger" end + end + + describe "update attributes" do + before(:each) do + a = Article.get "big-bad-danger" rescue nil + a.destroy if a + @art = Article.new(:title => "big bad danger") + @art.save + end it "should save" do @art['title'].should == "big bad danger" @art.update_attributes('date' => Time.now, :title => "super danger") loaded = Article.get @art.id loaded['title'].should == "super danger" end - end describe "a model with template values" do