From 06df51841a225099333899349af0d46708dbec59 Mon Sep 17 00:00:00 2001 From: Mat Brown Date: Thu, 22 Oct 2009 10:20:44 -0400 Subject: [PATCH] Fix instance_eval calls to association proxies In the current stable, ActiveRecord::Associations::AssociationProxy#method_missing calls yield() if a block is given, causing the block to always be evaluated in its calling context. However, in the case of instance_eval, correct behavior requires that the block be passed directly to the @target, rather than being evaluated inside a different block. Incidentally, this also simplifies the code slightly. --- .../associations/association_proxy.rb | 8 ++------ .../associations/has_many_associations_test.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb index 241b9bf..1e8a271 100644 --- a/activerecord/lib/active_record/associations/association_proxy.rb +++ b/activerecord/lib/active_record/associations/association_proxy.rb @@ -208,18 +208,14 @@ module ActiveRecord private # Forwards any missing method call to the \target. - def method_missing(method, *args) + def method_missing(method, *args, &block) if load_target unless @target.respond_to?(method) message = "undefined method `#{method.to_s}' for \"#{@target}\":#{@target.class.to_s}" raise NoMethodError, message end - if block_given? - @target.send(method, *args) { |*block_args| yield(*block_args) } - else - @target.send(method, *args) - end + @target.send(method, *args, &block) end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 23a1071..28adea1 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1118,5 +1118,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase client = firm.clients_using_primary_key.create!(:name => 'test') assert_equal firm.name, client.firm_name end + + def test_normal_method_call_in_association_proxy + assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.first.title + end + + def test_instance_eval_in_association_proxy + assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.first.instance_eval{title} + end end -- 1.6.0.4