From b4b3655300b589f555f8d3b55067c907077e2aba Mon Sep 17 00:00:00 2001 From: =?utf8?q?Johan=20S=C3=B8rensen?= Date: Wed, 12 Sep 2007 22:42:47 +0200 Subject: [PATCH] - Need to submit JSON fool - Fixed new? detection --- lib/couch_object/document.rb | 36 +++++++++++++++++++++--------------- spec/document_spec.rb | 17 ++++++++++++++--- 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/lib/couch_object/document.rb b/lib/couch_object/document.rb index f719ca7..60ee361 100644 --- a/lib/couch_object/document.rb +++ b/lib/couch_object/document.rb @@ -4,25 +4,22 @@ module CouchObject def initialize(db, attributes={}) @db = db - @attributes = attributes - @original_id = attributes["_id"] - end - attr_accessor :attributes - - def id - attributes["_id"] + @attributes = attributes.dup + @id = @attributes.delete("_id") + @revision = @attributes.delete("_rev") end + attr_accessor :attributes, :id, :revision def id=(new_id) - attributes["_id"] = new_id - end - - def revision - attributes["_rev"] + if new? + attributes["_id"] = @id = new_id + else + nil + end end def new? - @original_id.nil? + @id.nil? && @revision.nil? end def each(&blk) @@ -33,13 +30,22 @@ module CouchObject new? ? create : update end + def to_json + if id.nil? + opts = {} + else + opts = {"_id" => id} + end + attributes.merge(opts).to_json + end + protected def create - @db.post("", attributes) + @db.post("", self.to_json) end def update - @db.put(id, attributes) + @db.put(id, self.to_json) end end end \ No newline at end of file diff --git a/spec/document_spec.rb b/spec/document_spec.rb index f943338..d639722 100644 --- a/spec/document_spec.rb +++ b/spec/document_spec.rb @@ -27,7 +27,7 @@ describe CouchObject::Document do doc.id.should == nil end - it "should have an assignable id" do + it "should have an assignable id if new document" do doc = CouchObject::Document.new(@db) doc.id = "fubar" doc.id.should == "fubar" @@ -50,15 +50,26 @@ describe CouchObject::Document do doc.map {|attrib| attrib } end + it "should be JSONable" do + doc = CouchObject::Document.new(@db, {"foo" => "bar"}) + doc.to_json.should == JSON.unparse({"foo" => "bar"}) + end + + it "should be JSONable and include _id if id= is set" do + doc = CouchObject::Document.new(@db, {"foo" => "bar"}) + doc.id = "quux" + doc.to_json.should == JSON.unparse({"foo" => "bar", "_id" => "quux"}) + end + it "should POST to the database with create" do doc = CouchObject::Document.new(@db, {"foo" => "bar"}) - @db.should_receive(:post).with("", {"foo" => "bar"}).and_return(resp = mock("response")) + @db.should_receive(:post).with("", doc.to_json).and_return(resp = mock("response")) doc.save end it "should PUT to the database with create" do doc = CouchObject::Document.new(@db, @test_data) - @db.should_receive(:put).with(@test_data["_id"], @test_data).and_return(resp = mock("response")) + @db.should_receive(:put).with(@test_data["_id"], doc.to_json).and_return(resp = mock("response")) doc.save end -- 2.11.4.GIT