Skip to content

Commit 7a53b1c

Browse files
p-mongojohnnyshieldsp
authored
MONGOID-5105 Allow block form in Mongoid::Association::EmbedsMany::Proxy#count (#5060)
* MONGOID-5105 Mongoid::Association::EmbedsMany::Proxy should allow block form for #count to make it congruent with #any?, #none?, #all?, etc. Example: Person.addresses.count {|a| a.country == "FR" } I've also added additional tests for other methods. * MONGOID-5105 Update docs * MONGOID-5105 Fix specs on Ruby 2.3 and 2.4 * MONGOID-5105 - .create --> .create! in spec - Update docs * MONGOID-5105 improve spec robustness * MONGOID-5105 separate the tests * MONGOID-5105 remove Ruby 2.5+ requirement Co-authored-by: shields <[email protected]> Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent 5fcbce2 commit 7a53b1c

File tree

3 files changed

+378
-126
lines changed

3 files changed

+378
-126
lines changed

lib/mongoid/association/embedded/embeds_many/proxy.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,26 @@ def clear
102102
#
103103
# Use #size if you want the total number of documents.
104104
#
105+
# If args or block are present, #count will delegate to the
106+
# #count method on +target+ and will include both persisted
107+
# and non-persisted documents.
108+
#
105109
# @example Get the count of persisted documents.
106110
# person.addresses.count
107111
#
112+
# @example Get the count of all documents matching a block.
113+
# person.addresses.count { |a| a.country == "FR" }
114+
#
115+
# @example Use #persisted? inside block to count persisted documents.
116+
# person.addresses.count { |a| a.persisted? && a.country == "FR" }
117+
#
118+
# @param [ Object, Array<Object> ] args Args to delegate to the target.
119+
#
108120
# @return [ Integer ] The total number of persisted embedded docs, as
109121
# flagged by the #persisted? method.
110-
def count
122+
def count(*args, &block)
123+
return _target.count(*args, &block) if args.any? || block
124+
111125
_target.select { |doc| doc.persisted? }.size
112126
end
113127

0 commit comments

Comments
 (0)