Permalink
Browse files

Merge branch 'master' of github.com:jnunemaker/mongomapper

  • Loading branch information...
2 parents 054c7ce + 3b5fd1e commit 767049c0bd60d88fda17c248a41581808e2a849f @jnunemaker jnunemaker committed Jan 28, 2010
@@ -1,12 +1,12 @@
module MongoMapper
module EmbeddedDocument
extend DescendantAppends
-
+
def self.included(model)
model.class_eval do
include InstanceMethods
extend ClassMethods
-
+
extend Plugins
plugin Plugins::Associations
plugin Plugins::Clone
@@ -19,16 +19,22 @@ def self.included(model)
plugin Plugins::Serialization
plugin Plugins::Validations
- attr_accessor :_root_document
+ attr_accessor :_root_document, :_parent_document
end
-
+
super
end
module ClassMethods
def embeddable?
true
end
+
+ def embedded_in(owner_name)
+ define_method(owner_name) do
+ self._parent_document
+ end
+ end
end
module InstanceMethods
@@ -38,7 +44,7 @@ def save(options={})
end
result
end
-
+
def save!(options={})
if result = _root_document.try(:save!, options)
@new = false
@@ -41,6 +41,7 @@ def _root_document
def assign_root_document(*docs)
docs.each do |doc|
doc._root_document = _root_document
+ doc._parent_document = owner
end
end
end
@@ -15,6 +15,7 @@ def setup
@pet_class = EDoc do
key :name, String
end
+ @pet_class.embedded_in :person
@person_class = EDoc do
key :name, String
end
@@ -133,6 +134,17 @@ def setup
doc.people.first._root_document.should == doc
doc.people.first.pets.first._root_document.should == doc
end
+ should "create a reference to the owning document for all embedded documents before save" do
+ doc = @klass.new
+ meg = @person_class.new(:name => 'Meg')
+ pet = @pet_class.new(:name => 'Sparky', :species => 'Dog')
+
+ doc.people << meg
+ meg.pets << pet
+
+ doc.people.first._parent_document.should == doc
+ doc.people.first.pets.first._parent_document.should == doc.people.first
+ end
should "create a reference to the root document for all embedded documents" do
sparky = @pet_class.new(:name => 'Sparky', :species => 'Dog')
@@ -145,6 +157,32 @@ def setup
doc.people.first._root_document.should == doc
doc.people.first.pets.first._root_document.should == doc
end
+ should "create a reference to the owning document for all embedded documents" do
+ doc = @klass.new
+ meg = @person_class.new(:name => 'Meg')
+ pet = @pet_class.new(:name => 'Sparky', :species => 'Dog')
+
+ doc.people << meg
+ meg.pets << pet
+ doc.save
+
+ doc.reload
+ doc.people.first._parent_document.should == doc
+ doc.people.first.pets.first._parent_document.should == doc.people.first
+ end
+
+ should "create embedded_in relationship for embedded docs" do
+ doc = @klass.new
+ meg = @person_class.new(:name => 'Meg')
+ pet = @pet_class.new(:name => 'Sparky', :species => 'Dog')
+
+ doc.people << meg
+ meg.pets << pet
+ doc.save
+
+ doc.reload
+ doc.people.first.pets.first.person.should == doc.people.first
+ end
end
should "allow finding by id" do

0 comments on commit 767049c

Please sign in to comment.