Permalink
Browse files

Ensure NamedScope#any? uses COUNT query wherever possible. [#680 stat…

…e:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
1 parent 2681685 commit 93e10f9911fb2a096681ee0a0bc82487a9a06c44 @DefV DefV committed with lifo Jul 23, 2008
Showing with 31 additions and 1 deletion.
  1. +9 −1 activerecord/lib/active_record/named_scope.rb
  2. +22 −0 activerecord/test/cases/named_scope_test.rb
@@ -103,7 +103,7 @@ class Scope
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 @@ def empty?
@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
@@ -184,6 +184,28 @@ def test_empty_should_not_load_results
end
end
+ def test_any_should_not_load_results
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:empty?).returns(true)
+ assert !topics.any?
+ end
+ end
+
+ def test_any_should_call_proxy_found_if_using_a_block
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:empty?).never
+ topics.any? { true }
+ end
+ end
+
+ def test_any_should_not_fire_query_if_named_scope_loaded
+ topics = Topic.base
+ topics.collect # force load
+ assert_no_queries { assert topics.any? }
+ end
+
def test_should_build_with_proxy_options
topic = Topic.approved.build({})
assert topic.approved

4 comments on commit 93e10f9

@nicksieger

This commit broke an AR test that is still failing in edge as of this comment.

See http://gist.github.com/4339

@ryanb
ryanb commented on 93e10f9 Aug 8, 2008

I ran into this before too. You need to update mocha (gem install mocha). See this thread for details.

@ryanb
ryanb commented on 93e10f9 Aug 8, 2008

I have added a ticket about this issue along with a patch for a fix.

@nicksieger

Thanks ryanb!

Please sign in to comment.