From f396c01db25e45d1c2defc7dbb6f330f33453d04 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 17 Aug 2012 16:20:48 +0100 Subject: Optimize instantiation for models which don't use serialize Those z's were hard to type. --- .../attribute_methods/serialization.rb | 33 +++++++++++++--------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 49ab3ab808..e6f848df22 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -44,6 +44,24 @@ module ActiveRecord end end + # This is only added to the model when serialize is called, which + # ensures we do not make model instantiation slower when + # serialization is not used. + module InitializeAttributes #:nodoc: + def initialize_attributes(attributes, options = {}) + serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized + super(attributes, options) + + serialized_attributes.each do |key, coder| + if attributes.key?(key) + attributes[key] = Attribute.new(coder, attributes[key], serialized) + end + end + + attributes + end + end + module ClassMethods # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, # then specify the name of that attribute using this method and it will be handled automatically. @@ -61,6 +79,8 @@ module ActiveRecord # serialize :preferences # end def serialize(attr_name, class_name = Object) + extend InitializeAttributes + coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) } class_name else @@ -72,19 +92,6 @@ module ActiveRecord self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder) end - def initialize_attributes(attributes, options = {}) #:nodoc: - serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized - super(attributes, options) - - serialized_attributes.each do |key, coder| - if attributes.key?(key) - attributes[key] = Attribute.new(coder, attributes[key], serialized) - end - end - - attributes - end - private def attribute_cast_code(attr_name) -- cgit v1.2.3