From bfbdeeae3080c89a0b27e42d684cbeb6206c6f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 4 Jul 2010 15:57:44 +0200 Subject: [PATCH] Use bind instead of instance_exec cause it may be causing memory leaks. Also, provide a simpler and sane implementation for scoped. [#5044 state:resolved] --- activerecord/lib/active_record/named_scope.rb | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 21a544a81017b..901d4c2f3df42 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -8,10 +8,7 @@ module NamedScope # # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope. def self.included(base) - base.class_eval do - extend ClassMethods - named_scope :scoped, lambda { |scope| scope } - end + base.extend ClassMethods end module ClassMethods @@ -19,6 +16,10 @@ def scopes read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {}) end + def scoped(scope, &block) + Scope.new(self, scope, &block) + end + # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query, # such as :conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions. # @@ -84,22 +85,22 @@ def scopes # assert_equal expected_options, Shirt.colored('red').proxy_options def named_scope(name, options = {}, &block) name = name.to_sym + scopes[name] = lambda do |parent_scope, *args| Scope.new(parent_scope, case options when Hash options when Proc if self.model_name != parent_scope.model_name - parent_scope.instance_exec(*args, &options) + options.bind(parent_scope).call(*args) else options.call(*args) end end, &block) end - (class << self; self end).instance_eval do - define_method name do |*args| - scopes[name].call(self, *args) - end + + singleton_class.send :define_method, name do |*args| + scopes[name].call(self, *args) end end end