Permalink
Browse files

Allow default_scope to accept a Proc.

  • Loading branch information...
seven1m authored and tenderlove committed Oct 15, 2010
1 parent d619b9d commit b1b26af9a2f1c2037f7c2167d747ed33cc639763
@@ -1143,7 +1143,12 @@ def default_scope(options = {})
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:
@@ -311,6 +311,17 @@ def test_default_scope
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
@@ -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

0 comments on commit b1b26af

Please sign in to comment.