From b1b26af9a2f1c2037f7c2167d747ed33cc639763 Mon Sep 17 00:00:00 2001 From: Tim Morgan Date: Thu, 14 Oct 2010 22:31:05 -0500 Subject: Allow default_scope to accept a Proc. --- activerecord/lib/active_record/base.rb | 7 ++++++- activerecord/test/cases/relation_scoping_test.rb | 11 +++++++++++ activerecord/test/models/post.rb | 6 ++++++ 3 files changed, 23 insertions(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 78b3507dd9..879f02ff6a 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1143,7 +1143,12 @@ MSG end def current_scoped_methods #:nodoc: - scoped_methods.last + method = scoped_methods.last + if method.respond_to?(:call) + unscoped(&method) + else + method + 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 64365c1d75..965bdacc1a 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 a3cb9c724a..61e782ff14 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 -- cgit v1.2.3