From 8cbad0293b134d56fb01e5f500010603b4c18cc7 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 17 Aug 2012 18:14:44 +0100 Subject: Optimize for the happy path Checking respond_to? incurs overhead, and most of the time when assigning attributes it will return true. So just handle the NoMethodError instead. --- .../lib/active_record/attribute_assignment.rb | 25 ++++++++++++---------- 1 file changed, 14 insertions(+), 11 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index 6992840040..e3feb91d30 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -97,22 +97,15 @@ module ActiveRecord attributes.each do |k, v| if k.include?("(") multi_parameter_attributes << [ k, v ] - elsif respond_to?("#{k}=") - if v.is_a?(Hash) - nested_parameter_attributes << [ k, v ] - else - send("#{k}=", v) - end + elsif v.is_a?(Hash) + nested_parameter_attributes << [ k, v ] else - raise(UnknownAttributeError, "unknown attribute: #{k}") + _assign_attribute(k, v) end end # assign any deferred nested attributes after the base attributes have been set - nested_parameter_attributes.each do |k,v| - send("#{k}=", v) - end - + nested_parameter_attributes.each { |k,v| _assign_attribute(k, v) } assign_multiparameter_attributes(multi_parameter_attributes) ensure @mass_assignment_options = previous_options @@ -130,6 +123,16 @@ module ActiveRecord private + def _assign_attribute(k, v) + public_send("#{k}=", v) + rescue NoMethodError + if respond_to?("#{k}=") + raise + else + raise UnknownAttributeError, "unknown attribute: #{k}" + end + end + # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done # by calling new on the column type or aggregation type (through composed_of) object with these parameters. # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate -- cgit v1.2.3