Skip to content

Commit

Permalink
Adding Document#_children
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Apr 19, 2010
1 parent 903232b commit f3660ad
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
22 changes: 21 additions & 1 deletion lib/mongoid/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ module Associations #:nodoc:
cattr_accessor :embedded
self.embedded = false

class_inheritable_accessor :associations
class_inheritable_accessor :associations, :_child_names
self.associations = {}
self._child_names = []

delegate :embedded, :embedded?, :to => "self.class"
end
Expand All @@ -28,6 +29,23 @@ def associations
self.class.associations
end

# Get all the child documents for this particular document.
#
# Example:
#
# <tt>person._children</tt>
#
# Returns:
#
# The +Document+s for each embedded association, if they exist.
def _children
self._child_names.inject([]) do |children, name|
association = send(name)
children.concat(association.to_a) unless association.blank?
children
end
end

# Update the one-to-one relational association for the name.
def update_association(name)
association = send(name)
Expand Down Expand Up @@ -123,6 +141,7 @@ def embedded_in(name, options = {}, &block)
# embedded_in :person, :inverse_of => :addresses
# end
def embeds_many(name, options = {}, &block)
self._child_names << name
associate(Associations::EmbedsMany, optionize(name, options, nil, &block))
end

Expand All @@ -148,6 +167,7 @@ def embeds_many(name, options = {}, &block)
# embedded_in :person
# end
def embeds_one(name, options = {}, &block)
self._child_names << name
opts = optionize(name, options, nil, &block)
type = Associations::EmbedsOne
associate(type, opts)
Expand Down
28 changes: 28 additions & 0 deletions spec/unit/mongoid/associations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,34 @@
end
end

describe "#_children" do

before do
@person = Person.new
end

context "when the associations exist" do

before do
@address = Address.new
@name = Name.new
@person.addresses << @address
@person.name = @name
end

it "returns all embeds_one and embeds_many associations" do
@person._children.size.should == 2
end
end

context "when associations are empty" do

it "does not include them" do
@person._children.should be_empty
end
end
end

describe ".embedded?" do

context "when the class is embedded" do
Expand Down

0 comments on commit f3660ad

Please sign in to comment.