From 6d83f5f02103f180bb4f9a28ed6ca5d1a2bb22ed Mon Sep 17 00:00:00 2001 From: Jan Date: Mon, 22 Nov 2010 18:58:09 +0800 Subject: [PATCH] shortcut to unscoped version of named_scope so instead of Post.unscoped.on_apple.first you can write Post.on_apple!.first --- activerecord/lib/active_record/named_scope.rb | 15 +++++++++++++++ activerecord/test/cases/relations_test.rb | 8 ++++++++ 2 files changed, 23 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 0f42156..922a23c 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -120,6 +120,8 @@ module ActiveRecord end singleton_class.send(:redefine_method, name, &scopes[name]) + + unscoped_shortcut_for_scope(name) end protected @@ -130,6 +132,19 @@ module ActiveRecord "Overwriting existing method #{self.name}.#{name}." end end + + private + + def unscoped_shortcut_for_scope(name) + unscoped_shortcut = "#{name}!".to_sym + + scopes[unscoped_shortcut] = lambda do |*args| + unscoped { send(name, *args) } + end + + singleton_class.send(:redefine_method, unscoped_shortcut, &scopes[unscoped_shortcut]) + end + end end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 535bcd4..3336df4 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -774,6 +774,14 @@ class RelationTest < ActiveRecord::TestCase assert_equal 'honda', FastCar.unscoped { FastCar.order_using_old_style.limit(1).first.name} end + def test_unscoped_shortcut + assert_equal 'honda', CoolCar.order_using_new_style!.limit(1).first.name + assert_equal 'honda', CoolCar.order_using_old_style!.limit(1).first.name + + assert_equal 'honda', FastCar.order_using_new_style!.limit(1).first.name + assert_equal 'honda', FastCar.order_using_old_style!.limit(1).first.name + end + def test_intersection_with_array relation = Author.where(:name => "David") rails_author = relation.first -- 1.7.3.2