Permalink
Browse files

Model.scoped now returns a relation if invoked without any arguments

  Example :

    posts = Post.scoped
    posts.size # Fires "select count(*) from  posts" and returns the count
    posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
  • Loading branch information...
1 parent 7f5d44b commit 2e79ec71a542c2d2e7bedbe12eda0b5e177fb0e0 @lifo lifo committed Dec 25, 2009
Showing with 25 additions and 11 deletions.
  1. +19 −11 activerecord/lib/active_record/named_scope.rb
  2. +6 −0 activerecord/test/cases/relations_test.rb
@@ -6,18 +6,26 @@ module ActiveRecord
module NamedScope
extend ActiveSupport::Concern
- # All subclasses of ActiveRecord::Base have one named scope:
- # * <tt>scoped</tt> - which allows for the creation of anonymous \scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
- #
- # These anonymous \scopes tend to be useful when procedurally generating complex queries, where passing
- # intermediate values (scopes) around as first-class objects is convenient.
- #
- # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.
- included do
- named_scope :scoped, lambda { |scope| scope }
- end
-
module ClassMethods
+ # Returns a relation if invoked without any arguments.
+ #
+ # posts = Post.scoped
+ # posts.size # Fires "select count(*) from posts" and returns the count
+ # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
+ #
+ # Returns an anonymous named scope if any options are supplied.
+ #
+ # shirts = Shirt.scoped(:conditions => {:color => 'red'})
+ # shirts = shirts.scoped(:include => :washing_instructions)
+ #
+ # Anonymous \scopes tend to be useful when procedurally generating complex queries, where passing
+ # intermediate values (scopes) around as first-class objects is convenient.
+ #
+ # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.
+ def scoped(options = {}, &block)
+ options.present? ? Scope.new(self, options, &block) : arel_table
+ end
+
def scopes
read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
end
@@ -12,6 +12,12 @@
class RelationTest < ActiveRecord::TestCase
fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments
+ def test_scoped
+ topics = Topic.scoped
+ assert_kind_of ActiveRecord::Relation, topics
+ assert_equal 4, topics.size
+ end
+
def test_finding_with_conditions
assert_equal Author.find(:all, :conditions => "name = 'David'"), Author.all.conditions("name = 'David'").to_a
end

0 comments on commit 2e79ec7

Please sign in to comment.