From 2105803010195a13a119c561ce198685de2da51b Mon Sep 17 00:00:00 2001 From: Jan De Poorter Date: Wed, 23 Jul 2008 12:50:16 +0200 Subject: [PATCH] Add any? to NamedScope so it doesn't load the whole dataset but does a count --- activerecord/lib/active_record/named_scope.rb | 10 +++++++++- activerecord/test/cases/named_scope_test.rb | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 080e3d0..d5a1c5f 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -103,7 +103,7 @@ module ActiveRecord attr_reader :proxy_scope, :proxy_options [].methods.each do |m| - unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/ + unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?|any?)/ delegate m, :to => :proxy_found end end @@ -140,6 +140,14 @@ module ActiveRecord @found ? @found.empty? : count.zero? end + def any? + if block_given? + proxy_found.any? { |*block_args| yield(*block_args) } + else + !empty? + end + end + protected def proxy_found @found || load_found diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 0c1eb23..87d770e 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -183,6 +183,18 @@ class NamedScopeTest < ActiveRecord::TestCase topics.empty? # use loaded (no query) end end + + def test_any_should_not_load_results + topics = Topic.base + topics.expects(:empty?).returns(true) + assert !topics.any? + end + + def test_any_should_call_proxy_found_if_using_a_block + topics = Topic.base + topics.expects(:empty?).never + topics.any? { true } + end def test_should_build_with_proxy_options topic = Topic.approved.build({}) -- 1.5.6.rc0.29.g3beb5