Permalink
Browse files

Optimize instantiation for models which don't use serialize

Those z's were hard to type.
  • Loading branch information...
1 parent 1b2c907 commit f396c01db25e45d1c2defc7dbb6f330f33453d04 @jonleighton jonleighton committed Aug 17, 2012
Showing with 20 additions and 13 deletions.
  1. +20 −13 activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -44,6 +44,24 @@ def serialize
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 ClassMethods
# 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 @@ def serialize(attr_name, class_name = Object)
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)

0 comments on commit f396c01

Please sign in to comment.