Skip to content

Commit

Permalink
Modified relations/targets/eumerable and relations/referenced/many ea…
Browse files Browse the repository at this point in the history
…ch methods to return an Enumerator when no block is given
  • Loading branch information
robotlovesyou authored and durran committed Oct 3, 2012
1 parent a03ad2e commit 9a7650d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/mongoid/relations/referenced/many.rb
Expand Up @@ -165,7 +165,11 @@ def destroy_all(conditions = nil)
#
# @since 2.1.0
def each
target.each { |doc| yield(doc) if block_given? }
if block_given?
target.each { |doc| yield(doc) }
else
to_enum
end
end

# Determine if any documents in this relation exist in the database.
Expand Down
10 changes: 10 additions & 0 deletions lib/mongoid/relations/targets/enumerable.rb
Expand Up @@ -139,15 +139,25 @@ def delete_if(&block)
# the cursor while loading the documents and then iterates over the
# _added docs.
#
# If no block is passed then it returns an enumerator containing all
# docs.
#
# @example Iterate over the enumerable.
# enumerable.each do |doc|
# puts doc
# end
#
# @example return an enumerator containing all the docs
#
# a = enumerable.each
#
# @return [ true ] That the enumerable is now _loaded.
#
# @since 2.1.0
def each
unless block_given?
return to_enum
end
if _loaded?
_loaded.each_pair do |id, doc|
yield(doc)
Expand Down
16 changes: 16 additions & 0 deletions spec/mongoid/relations/targets/enumerable_spec.rb
Expand Up @@ -622,6 +622,22 @@
end
end
end

context "when no block is passed" do

let(:criteria) do
Post.where(person_id: person.id)
end

let!(:enumerable) do
described_class.new(criteria)
end

it "returns an enumerator" do
enumerable.each.class.include?(Enumerable).should be_true
end

end
end

describe "#entries" do
Expand Down

0 comments on commit 9a7650d

Please sign in to comment.