Skip to content
Browse files

Make NamedScope#size behave identically to AssociationCollection#size. [

#933 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
1 parent c036134 commit 7f179f8540ab92dbd9d3e650b465de5b694d93d4 @tomstuart tomstuart committed with lifo
Showing with 20 additions and 1 deletion.
  1. +5 −1 activerecord/lib/active_record/named_scope.rb
  2. +15 −0 activerecord/test/cases/named_scope_test.rb
View
6 activerecord/lib/active_record/named_scope.rb
@@ -101,7 +101,7 @@ def named_scope(name, options = {}, &block)
class Scope
attr_reader :proxy_scope, :proxy_options
- NON_DELEGATE_METHODS = %w(nil? send object_id class extend find 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? respond_to?).to_set
[].methods.each do |m|
unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s)
delegate m, :to => :proxy_found
@@ -136,6 +136,10 @@ def last(*args)
end
end
+ def size
+ @found ? @found.length : count
+ end
+
def empty?
@found ? @found.empty? : count.zero?
end
View
15 activerecord/test/cases/named_scope_test.rb
@@ -256,4 +256,19 @@ def test_rand_should_select_a_random_object_from_proxy
def test_should_use_where_in_query_for_named_scope
assert_equal Developer.find_all_by_name('Jamis'), Developer.find_all_by_id(Developer.jamises)
end
+
+ def test_size_should_use_count_when_results_are_not_loaded
+ topics = Topic.base
+ assert_queries(1) do
+ assert_sql(/COUNT/i) { topics.size }
+ end
+ end
+
+ def test_size_should_use_length_when_results_are_loaded
+ topics = Topic.base
+ topics.reload # force load
+ assert_no_queries do
+ topics.size # use loaded (no query)
+ end
+ end
end

0 comments on commit 7f179f8

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