提交 7b391977 编写于 作者: F fatkodima

Avoid allocating extra hash and arrays when as_json is called without options

Co-authored-by: NEugene Kenny <elkenny@gmail.com>
上级 b0d0feab
......@@ -121,17 +121,17 @@ module Serialization
# user.serializable_hash(include: { notes: { only: 'title' }})
# # => {"name" => "Napoleon", "notes" => [{"title"=>"Battle of Austerlitz"}]}
def serializable_hash(options = nil)
options ||= {}
attribute_names = attributes.keys
return serializable_attributes(attribute_names) unless options
if only = options[:only]
attribute_names &= Array(only).map(&:to_s)
elsif except = options[:except]
attribute_names -= Array(except).map(&:to_s)
end
hash = {}
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
hash = serializable_attributes(attribute_names)
Array(options[:methods]).each { |m| hash[m.to_s] = send(m) }
......@@ -165,6 +165,10 @@ def serializable_hash(options = nil)
# end
alias :read_attribute_for_serialization :send
def serializable_attributes(attribute_names)
attribute_names.index_with { |n| read_attribute_for_serialization(n) }
end
# Add associations specified via the <tt>:include</tt> option.
#
# Expects a block that takes as arguments:
......
......@@ -11,10 +11,12 @@ module Serialization
end
def serializable_hash(options = nil)
options = options ? options.dup : {}
if self.class.has_attribute?(self.class.inheritance_column)
options = options ? options.dup : {}
options[:except] = Array(options[:except]).map(&:to_s)
options[:except] |= Array(self.class.inheritance_column)
options[:except] = Array(options[:except]).map(&:to_s)
options[:except] |= Array(self.class.inheritance_column)
end
super(options)
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册