Skip to content

Commit

Permalink
Avoid allocating extra hash and arrays when as_json is called without…
Browse files Browse the repository at this point in the history
… options

Co-authored-by: Eugene Kenny <elkenny@gmail.com>
  • Loading branch information
fatkodima and eugeneius committed May 17, 2020
1 parent b0d0fea commit 7b39197
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
12 changes: 8 additions & 4 deletions activemodel/lib/active_model/serialization.rb
Expand Up @@ -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) }

Expand Down Expand Up @@ -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:
Expand Down
8 changes: 5 additions & 3 deletions activerecord/lib/active_record/serialization.rb
Expand Up @@ -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
Expand Down

0 comments on commit 7b39197

Please sign in to comment.