From 25f48f49aa4cc35f5877ae5b434a81f00ca7353c Mon Sep 17 00:00:00 2001 From: Michael Oberegger Date: Fri, 30 May 2025 13:01:44 -0400 Subject: [PATCH 1/2] Optimize extract to save on memory allocation --- lib/jbuilder.rb | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index b12624be..e757faa9 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -58,7 +58,7 @@ def set!(key, value = BLANK, *args, &block) else # json.author @post.creator, :name, :email_address # { "author": { "name": "David", "email_address": "david@loudthinking.com" } } - _merge_block(key){ extract! value, *args } + _merge_block(key){ _extract value, args } end _set_value key, result @@ -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 @@ -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 @@ -281,8 +277,16 @@ 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)) } + attributes.each{ |key| _set_value key, _format_keys(object[key]) } end def _extract_method_values(object, attributes) From 06224642c48f1d521139b9a348336fbe02887844 Mon Sep 17 00:00:00 2001 From: Michael Oberegger Date: Mon, 2 Jun 2025 11:13:59 -0400 Subject: [PATCH 2/2] Back to fetch --- lib/jbuilder.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index e757faa9..fd91852b 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -286,7 +286,7 @@ def _extract(object, attributes) end def _extract_hash_values(object, attributes) - attributes.each{ |key| _set_value key, _format_keys(object[key]) } + attributes.each{ |key| _set_value key, _format_keys(object.fetch(key)) } end def _extract_method_values(object, attributes)