Skip to content

Commit 535327a

Browse files
authored
Merge pull request #598 from affinity/moberegger/optimize_extract
Optimize internal `extract!` calls to save on memory allocation
2 parents 6445930 + 0622464 commit 535327a

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

lib/jbuilder.rb

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def set!(key, value = BLANK, *args, &block)
6464
else
6565
# json.author @post.creator, :name, :email_address
6666
# { "author": { "name": "David", "email_address": "[email protected]" } }
67-
_merge_block(key){ extract! value, *args }
67+
_merge_block(key){ _extract value, args }
6868
end
6969

7070
_set_value key, result
@@ -221,7 +221,7 @@ def array!(collection = [], *attributes, &block)
221221
elsif ::Kernel.block_given?
222222
_map_collection(collection, &block)
223223
elsif attributes.any?
224-
_map_collection(collection) { |element| extract! element, *attributes }
224+
_map_collection(collection) { |element| _extract element, attributes }
225225
else
226226
_format_keys(collection.to_a)
227227
end
@@ -247,18 +247,14 @@ def array!(collection = [], *attributes, &block)
247247
#
248248
# json.(@person, :name, :age)
249249
def extract!(object, *attributes)
250-
if ::Hash === object
251-
_extract_hash_values(object, attributes)
252-
else
253-
_extract_method_values(object, attributes)
254-
end
250+
_extract object, attributes
255251
end
256252

257253
def call(object, *attributes, &block)
258254
if ::Kernel.block_given?
259255
array! object, &block
260256
else
261-
extract! object, *attributes
257+
_extract object, attributes
262258
end
263259
end
264260

@@ -287,6 +283,14 @@ def target!
287283

288284
private
289285

286+
def _extract(object, attributes)
287+
if ::Hash === object
288+
_extract_hash_values(object, attributes)
289+
else
290+
_extract_method_values(object, attributes)
291+
end
292+
end
293+
290294
def _extract_hash_values(object, attributes)
291295
attributes.each{ |key| _set_value key, _format_keys(object.fetch(key)) }
292296
end

0 commit comments

Comments
 (0)