Permalink
Browse files

Merge the has_finder gem, renamed as 'named_scope'. Closes #11404 [nk…

…allen]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9084 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
technoweenie committed Mar 24, 2008
1 parent 5bf4cbb commit 081ddb6f24d70794ee9e071d3ed5302f52b26c4d
View
@@ -1,5 +1,19 @@
*SVN*
+* Merge the has_finder gem, renamed as 'named_scope'. #11404 [nkallen]
+
+ class Article < ActiveRecord::Base
+ has_finder :published, :conditions => {:published => true}
+ has_finder :popular, :conditions => ...
+ end
+
+ Article.published.paginate(:page => 1)
+ Article.published.popular.count
+ Article.popular.find(:first)
+ Article.popular.find(:all, :conditions => {...})
+
+ See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
+
* Add has_one :through support. #4756 [thechrisoshow]
* Migrations: create_table supports primary_key_prefix_type. #10314 [student, thechrisoshow]
@@ -37,6 +37,7 @@
end
require 'active_record/base'
+require 'active_record/named_scope'
require 'active_record/observer'
require 'active_record/query_cache'
require 'active_record/validations'
@@ -64,6 +65,7 @@
include ActiveRecord::Observing
include ActiveRecord::Timestamp
include ActiveRecord::Associations
+ include ActiveRecord::NamedScope
include ActiveRecord::AssociationPreload
include ActiveRecord::Aggregations
include ActiveRecord::Transactions
@@ -1133,7 +1133,7 @@ def collection_accessor_methods(reflection, association_proxy_class, writer = tr
end
end
end
-
+
def add_multiple_associated_save_callbacks(association_name)
method_name = "validate_associated_records_for_#{association_name}".to_sym
ivar = "@#{association_name}"
@@ -41,7 +41,7 @@ def delete_all
delete(@target)
reset_target!
end
-
+
# Calculate sum using SQL, not Enumerable
def sum(*args)
if block_given?
@@ -168,8 +168,10 @@ def method_missing(method, *args)
else
super
end
- else
- @reflection.klass.send(:with_scope, construct_scope) do
+ elsif @reflection.klass.scopes.include?(method)
+ @reflection.klass.scopes[method].call(self, *args)
+ else
+ with_scope(construct_scope) do
if block_given?
@reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
else
@@ -119,6 +119,10 @@ def merge_options_from_reflection!(options)
)
end
+ def with_scope(*args, &block)
+ @reflection.klass.send :with_scope, *args, &block
+ end
+
private
def method_missing(method, *args)
if load_target
@@ -167,7 +167,10 @@ def construct_sql
def construct_scope
create_scoping = {}
set_belongs_to_association_for(create_scoping)
- { :find => { :conditions => @finder_sql, :readonly => false, :order => @reflection.options[:order], :limit => @reflection.options[:limit] }, :create => create_scoping }
+ {
+ :find => { :conditions => @finder_sql, :readonly => false, :order => @reflection.options[:order], :limit => @reflection.options[:limit] },
+ :create => create_scoping
+ }
end
end
end
@@ -139,8 +139,10 @@ def method_missing(method, *args)
else
super
end
+ elsif @reflection.klass.scopes.include?(method)
+ @reflection.klass.scopes[method].call(self, *args)
else
- @reflection.klass.send(:with_scope, construct_scope) do
+ with_scope construct_scope do
if block_given?
@reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
else
@@ -0,0 +1,128 @@
+module ActiveRecord
+ module NamedScope
+ # All subclasses of ActiveRecord::Base have two named_scopes:
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly:
+ #
+ # Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)
+ #
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
+ # intermediate values (scopes) around as first-class objects is convenient.
+ def self.included(base)
+ base.class_eval do
+ extend ClassMethods
+ named_scope :all
+ named_scope :scoped, lambda { |scope| scope }
+ end
+ end
+
+ module ClassMethods
+ def scopes
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
+ end
+
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'}
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
+ # end
+ #
+ # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
+ #
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
+ #
+ # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
+ #
+ # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to
+ # <tt>has_many</tt> associations. If,
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :shirts
+ # end
+ #
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
+ # only shirts.
+ #
+ # Named scopes can also be procedural.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :colored, lambda { |color|
+ # { :conditions => { :color => color } }
+ # }
+ # end
+ #
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
+ #
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'} do
+ # def dom_id
+ # 'red_shirts'
+ # end
+ # end
+ # end
+ #
+ def named_scope(name, options = {}, &block)
+ scopes[name] = lambda do |parent_scope, *args|
+ Scope.new(parent_scope, case options
+ when Hash
+ options
+ when Proc
+ options.call(*args)
+ end, &block)
+ end
+ (class << self; self end).instance_eval do
+ define_method name do |*args|
+ scopes[name].call(self, *args)
+ end
+ end
+ end
+ end
+
+ class Scope
+ attr_reader :proxy_scope, :proxy_options
+ [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ }
+ delegate :scopes, :with_scope, :to => :proxy_scope
+
+ def initialize(proxy_scope, options, &block)
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
+ extend Module.new(&block) if block_given?
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
+ end
+
+ def reload
+ load_found; self
+ end
+
+ protected
+ def proxy_found
+ @found || load_found
+ end
+
+ private
+ def method_missing(method, *args, &block)
+ if scopes.include?(method)
+ scopes[method].call(self, *args)
+ else
+ with_scope :find => proxy_options do
+ proxy_scope.send(method, *args, &block)
+ end
+ end
+ end
+
+ def load_found
+ @found = find(:all)
+ end
+ end
+ end
+end
@@ -61,16 +61,17 @@ def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
def test_eager_association_loading_with_has_many_sti
topics = Topic.find(:all, :include => :replies, :order => 'topics.id')
- assert_equal topics(:first, :second), topics
+ first, second, = topics(:first).replies.size, topics(:second).replies.size
assert_no_queries do
- assert_equal 1, topics[0].replies.size
- assert_equal 0, topics[1].replies.size
+ assert_equal first, topics[0].replies.size
+ assert_equal second, topics[1].replies.size
end
end
def test_eager_association_loading_with_belongs_to_sti
replies = Reply.find(:all, :include => :topic, :order => 'topics.id')
- assert_equal [topics(:second)], replies
+ assert replies.include?(topics(:second))
+ assert !replies.include?(topics(:first))
assert_equal topics(:first), assert_no_queries { replies.first.topic }
end
@@ -477,7 +477,7 @@ def test_initialize_with_invalid_attribute
def test_load
topics = Topic.find(:all, :order => 'id')
- assert_equal(2, topics.size)
+ assert_equal(4, topics.size)
assert_equal(topics(:first).title, topics.first.title)
end
@@ -549,10 +549,11 @@ def test_table_name_guesses
end
def test_destroy_all
- assert_equal 2, Topic.count
-
- Topic.destroy_all "author_name = 'Mary'"
- assert_equal 1, Topic.count
+ original_count = Topic.count
+ topics_by_mary = Topic.count(:conditions => mary = "author_name = 'Mary'")
+
+ Topic.destroy_all mary
+ assert_equal original_count - topics_by_mary, Topic.count
end
def test_destroy_many
@@ -562,8 +563,9 @@ def test_destroy_many
end
def test_delete_many
- Topic.delete([1, 2])
- assert_equal 0, Topic.count
+ original_count = Topic.count
+ Topic.delete(deleting = [1, 2])
+ assert_equal original_count - deleting.size, Topic.count
end
def test_boolean_attributes
@@ -588,21 +590,21 @@ def test_decrement_counter
end
def test_update_all
- assert_equal 2, Topic.update_all("content = 'bulk updated!'")
+ assert_equal Topic.count, Topic.update_all("content = 'bulk updated!'")
assert_equal "bulk updated!", Topic.find(1).content
assert_equal "bulk updated!", Topic.find(2).content
- assert_equal 2, Topic.update_all(['content = ?', 'bulk updated again!'])
+ assert_equal Topic.count, Topic.update_all(['content = ?', 'bulk updated again!'])
assert_equal "bulk updated again!", Topic.find(1).content
assert_equal "bulk updated again!", Topic.find(2).content
- assert_equal 2, Topic.update_all(['content = ?', nil])
+ assert_equal Topic.count, Topic.update_all(['content = ?', nil])
assert_nil Topic.find(1).content
end
def test_update_all_with_hash
assert_not_nil Topic.find(1).last_read
- assert_equal 2, Topic.update_all(:content => 'bulk updated with hash!', :last_read => nil)
+ assert_equal Topic.count, Topic.update_all(:content => 'bulk updated with hash!', :last_read => nil)
assert_equal "bulk updated with hash!", Topic.find(1).content
assert_equal "bulk updated with hash!", Topic.find(2).content
assert_nil Topic.find(1).last_read
@@ -637,7 +639,9 @@ def test_update_many
end
def test_delete_all
- assert_equal 2, Topic.delete_all
+ assert Topic.count > 0
+
+ assert_equal Topic.count, Topic.delete_all
end
def test_update_by_condition
@@ -804,17 +808,17 @@ def test_update_attributes
def test_update_attributes!
reply = Reply.find(2)
- assert_equal "The Second Topic's of the day", reply.title
+ assert_equal "The Second Topic of the day", reply.title
assert_equal "Have a nice day", reply.content
- reply.update_attributes!("title" => "The Second Topic's of the day updated", "content" => "Have a nice evening")
+ reply.update_attributes!("title" => "The Second Topic of the day updated", "content" => "Have a nice evening")
reply.reload
- assert_equal "The Second Topic's of the day updated", reply.title
+ assert_equal "The Second Topic of the day updated", reply.title
assert_equal "Have a nice evening", reply.content
- reply.update_attributes!(:title => "The Second Topic's of the day", :content => "Have a nice day")
+ reply.update_attributes!(:title => "The Second Topic of the day", :content => "Have a nice day")
reply.reload
- assert_equal "The Second Topic's of the day", reply.title
+ assert_equal "The Second Topic of the day", reply.title
assert_equal "Have a nice day", reply.content
assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(:title => nil, :content => "Have a nice evening") }
@@ -1770,7 +1774,7 @@ def test_to_xml_including_has_many_association
xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
assert_equal "<topic>", xml.first(7)
assert xml.include?(%(<replies type="array"><reply>))
- assert xml.include?(%(<title>The Second Topic's of the day</title>))
+ assert xml.include?(%(<title>The Second Topic of the day</title>))
end
def test_array_to_xml_including_has_many_association
@@ -542,7 +542,7 @@ def test_find_all_by_one_attribute_with_options
end
def test_find_all_by_array_attribute
- assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic's of the day"]).size
+ assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic of the day"]).size
end
def test_find_all_by_boolean_attribute
@@ -551,7 +551,7 @@ def test_find_all_by_boolean_attribute
assert topics.include?(topics(:first))
topics = Topic.find_all_by_approved(true)
- assert_equal 1, topics.size
+ assert_equal 3, topics.size
assert topics.include?(topics(:second))
end
@@ -563,8 +563,8 @@ def test_find_by_nil_attribute
def test_find_all_by_nil_attribute
topics = Topic.find_all_by_last_read nil
- assert_equal 1, topics.size
- assert_nil topics[0].last_read
+ assert_equal 3, topics.size
+ assert topics.collect(&:last_read).all?(&:nil?)
end
def test_find_by_nil_and_not_nil_attributes
@@ -123,7 +123,7 @@ def test_instantiation
end
def test_complete_instantiation
- assert_equal 2, @topics.size
+ assert_equal 4, @topics.size
assert_equal "The First Topic", @first.title
end
Oops, something went wrong.

0 comments on commit 081ddb6

Please sign in to comment.