Skip to content

Commit

Permalink
Make NamedScope#size behave identically to AssociationCollection#size. [
Browse files Browse the repository at this point in the history
#933 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
tomstuart authored and lifo committed Aug 29, 2008
1 parent c036134 commit 7f179f8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion activerecord/lib/active_record/named_scope.rb
Expand Up @@ -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
Expand Down Expand Up @@ -136,6 +136,10 @@ def last(*args)
end
end

def size
@found ? @found.length : count
end

def empty?
@found ? @found.empty? : count.zero?
end
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/named_scope_test.rb
Expand Up @@ -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.