提交 f396c01d 编写于 作者: J Jon Leighton

Optimize instantiation for models which don't use serialize

Those z's were hard to type.
上级 1b2c9077
......@@ -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)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册