Skip to content

Optimize internal extract! calls to save on memory allocation #598

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def set!(key, value = BLANK, *args, &block)
else
# json.author @post.creator, :name, :email_address
# { "author": { "name": "David", "email_address": "[email protected]" } }
_merge_block(key){ extract! value, *args }
_merge_block(key){ _extract value, args }
end

_set_value key, result
Expand Down Expand Up @@ -215,7 +215,7 @@ def array!(collection = [], *attributes, &block)
elsif ::Kernel.block_given?
_map_collection(collection, &block)
elsif attributes.any?
_map_collection(collection) { |element| extract! element, *attributes }
_map_collection(collection) { |element| _extract element, attributes }
else
_format_keys(collection.to_a)
end
Expand All @@ -241,18 +241,14 @@ def array!(collection = [], *attributes, &block)
#
# json.(@person, :name, :age)
def extract!(object, *attributes)
if ::Hash === object
_extract_hash_values(object, attributes)
else
_extract_method_values(object, attributes)
end
_extract object, attributes
end

def call(object, *attributes, &block)
if ::Kernel.block_given?
array! object, &block
else
extract! object, *attributes
_extract object, attributes
end
end

Expand Down Expand Up @@ -281,6 +277,14 @@ def target!

private

def _extract(object, attributes)
if ::Hash === object
_extract_hash_values(object, attributes)
else
_extract_method_values(object, attributes)
end
end

def _extract_hash_values(object, attributes)
attributes.each{ |key| _set_value key, _format_keys(object.fetch(key)) }
end
Expand Down