From d0251fd1adac2dc2d20a7e4b4f0c6e47960517c0 Mon Sep 17 00:00:00 2001 From: Tim Morgan Date: Thu, 14 Oct 2010 22:31:05 -0500 Subject: [PATCH] Allow default_scope to accept a Proc. --- activerecord/lib/active_record/base.rb | 6 +++++- activerecord/test/cases/relation_scoping_test.rb | 11 +++++++++++ activerecord/test/models/post.rb | 6 ++++++ 3 files changed, 22 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 78b3507..1736987 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1143,7 +1143,11 @@ MSG end def current_scoped_methods #:nodoc: - scoped_methods.last + if m = scoped_methods.last and m.is_a?(Proc) + unscoped { m.call } + else + scoped_methods.last + end end def reset_scoped_methods #:nodoc: diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 64365c1..965bdac 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -311,6 +311,17 @@ class DefaultScopingTest < ActiveRecord::TestCase assert_equal expected, received end + def test_default_scope_with_lambda + expected = Post.find_all_by_author_id(2) + PostForAuthor.selected_author = 2 + received = PostForAuthor.all + assert_equal expected, received + expected = Post.find_all_by_author_id(1) + PostForAuthor.selected_author = 1 + received = PostForAuthor.all + assert_equal expected, received + end + def test_default_scope_is_unscoped_on_find assert_equal 1, DeveloperCalledDavid.count assert_equal 11, DeveloperCalledDavid.unscoped.count diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index a3cb9c7..61e782f 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -113,3 +113,9 @@ class PostWithComment < ActiveRecord::Base self.table_name = 'posts' default_scope where("posts.comments_count > 0").order("posts.comments_count ASC") end + +class PostForAuthor < ActiveRecord::Base + self.table_name = 'posts' + cattr_accessor :selected_author + default_scope lambda { where(:author_id => PostForAuthor.selected_author) } +end -- 1.7.1