Skip to content
This repository
Browse code

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

…e:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit 93e10f9911fb2a096681ee0a0bc82487a9a06c44 1 parent 2681685
Jan De Poorter authored July 23, 2008 lifo committed July 23, 2008
10  activerecord/lib/active_record/named_scope.rb
@@ -103,7 +103,7 @@ class Scope
103 103
       attr_reader :proxy_scope, :proxy_options
104 104
 
105 105
       [].methods.each do |m|
106  
-        unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/
  106
+        unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?|any?)/
107 107
           delegate m, :to => :proxy_found
108 108
         end
109 109
       end
@@ -140,6 +140,14 @@ def empty?
140 140
         @found ? @found.empty? : count.zero?
141 141
       end
142 142
 
  143
+      def any?
  144
+        if block_given?
  145
+          proxy_found.any? { |*block_args| yield(*block_args) }
  146
+        else
  147
+          !empty?
  148
+        end
  149
+      end
  150
+
143 151
       protected
144 152
       def proxy_found
145 153
         @found || load_found
22  activerecord/test/cases/named_scope_test.rb
@@ -184,6 +184,28 @@ def test_empty_should_not_load_results
184 184
     end
185 185
   end
186 186
 
  187
+  def test_any_should_not_load_results
  188
+    topics = Topic.base
  189
+    assert_queries(1) do
  190
+      topics.expects(:empty?).returns(true)
  191
+      assert !topics.any?
  192
+    end
  193
+  end
  194
+
  195
+  def test_any_should_call_proxy_found_if_using_a_block
  196
+    topics = Topic.base
  197
+    assert_queries(1) do
  198
+      topics.expects(:empty?).never
  199
+      topics.any? { true }
  200
+    end
  201
+  end
  202
+
  203
+  def test_any_should_not_fire_query_if_named_scope_loaded
  204
+    topics = Topic.base
  205
+    topics.collect # force load
  206
+    assert_no_queries { assert topics.any? }
  207
+  end
  208
+
187 209
   def test_should_build_with_proxy_options
188 210
     topic = Topic.approved.build({})
189 211
     assert topic.approved

4 notes on commit 93e10f9

Nick Sieger

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

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

Ryan Bates

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

Ryan Bates

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

Nick Sieger

Thanks ryanb!

Please sign in to comment.
Something went wrong with that request. Please try again.