Skip to content

Commit 87f2915

Browse files
authored
Optimize internal extract! calls to save on memory allocation (#7)
* Optimize extract to save on memory allocation * Back to fetch
1 parent 0a67bbd commit 87f2915

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

lib/jbuilder.rb

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def set!(key, value = BLANK, *args, &block)
5858
else
5959
# json.author @post.creator, :name, :email_address
6060
# { "author": { "name": "David", "email_address": "david@loudthinking.com" } }
61-
_merge_block(key){ extract! value, *args }
61+
_merge_block(key){ _extract value, args }
6262
end
6363

6464
_set_value key, result
@@ -215,7 +215,7 @@ def array!(collection = [], *attributes, &block)
215215
elsif ::Kernel.block_given?
216216
_map_collection(collection, &block)
217217
elsif attributes.any?
218-
_map_collection(collection) { |element| extract! element, *attributes }
218+
_map_collection(collection) { |element| _extract element, attributes }
219219
else
220220
_format_keys(collection.to_a)
221221
end
@@ -241,18 +241,14 @@ def array!(collection = [], *attributes, &block)
241241
#
242242
# json.(@person, :name, :age)
243243
def extract!(object, *attributes)
244-
if ::Hash === object
245-
_extract_hash_values(object, attributes)
246-
else
247-
_extract_method_values(object, attributes)
248-
end
244+
_extract object, attributes
249245
end
250246

251247
def call(object, *attributes, &block)
252248
if ::Kernel.block_given?
253249
array! object, &block
254250
else
255-
extract! object, *attributes
251+
_extract object, attributes
256252
end
257253
end
258254

@@ -281,6 +277,14 @@ def target!
281277

282278
private
283279

280+
def _extract(object, attributes)
281+
if ::Hash === object
282+
_extract_hash_values(object, attributes)
283+
else
284+
_extract_method_values(object, attributes)
285+
end
286+
end
287+
284288
def _extract_hash_values(object, attributes)
285289
attributes.each{ |key| _set_value key, _format_keys(object.fetch(key)) }
286290
end

0 commit comments

Comments
 (0)