From 4e8c36a7417e5d447c9b15d5c61df0c014ee6d3b Mon Sep 17 00:00:00 2001 From: Chris Kampmeier Date: Mon, 16 Mar 2009 05:56:32 -0700 Subject: Implement #many? for NamedScope and AssociationCollection using #size [#1500 state:resolved] Signed-off-by: Pratik Naik --- .../lib/active_record/associations/association_collection.rb | 9 +++++++++ activerecord/lib/active_record/named_scope.rb | 11 ++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 26987dde97..e12f6be35d 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -302,6 +302,15 @@ module ActiveRecord end end + # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1. + def many? + if block_given? + method_missing(:many?) { |*block_args| yield(*block_args) } + else + size > 1 + end + end + def uniq(collection = self) seen = Set.new collection.inject([]) do |kept, record| diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 07f98dc743..e7151a3d47 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -109,7 +109,7 @@ module ActiveRecord class Scope attr_reader :proxy_scope, :proxy_options, :current_scoped_methods_when_defined - NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? respond_to?).to_set + NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? many? respond_to?).to_set [].methods.each do |m| unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s) delegate m, :to => :proxy_found @@ -168,6 +168,15 @@ module ActiveRecord end end + # Returns true if the named scope has more than 1 matching record. + def many? + if block_given? + proxy_found.many? { |*block_args| yield(*block_args) } + else + size > 1 + end + end + protected def proxy_found @found || load_found -- cgit v1.2.3