diff options
author | Jon Leighton <j@jonathanleighton.com> | 2012-08-17 16:20:48 +0100 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2012-08-17 18:22:29 +0100 |
commit | f396c01db25e45d1c2defc7dbb6f330f33453d04 (patch) | |
tree | fd22e26e16cffe266045711cef0ec8b093a860f9 | |
parent | 1b2c907727e4a698d9c2979958aa78a1b4bfdaa1 (diff) | |
download | rails-f396c01db25e45d1c2defc7dbb6f330f33453d04.tar.gz rails-f396c01db25e45d1c2defc7dbb6f330f33453d04.tar.bz2 rails-f396c01db25e45d1c2defc7dbb6f330f33453d04.zip |
Optimize instantiation for models which don't use serialize
Those z's were hard to type.
-rw-r--r-- | activerecord/lib/active_record/attribute_methods/serialization.rb | 33 |
1 files changed, 20 insertions, 13 deletions
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) |