Skip to content

Commit d43ee20

Browse files
authored
Merge pull request rails#52234 from kwstannard/indifferent
refactor HashWithIndifferentAccess#to_hash
2 parents 88924dd + ed5d646 commit d43ee20

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

activesupport/lib/active_support/hash_with_indifferent_access.rb

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -378,13 +378,10 @@ def compact
378378

379379
# Convert to a regular hash with string keys.
380380
def to_hash
381-
_new_hash = Hash.new
382-
set_defaults(_new_hash)
383-
384-
each do |key, value|
385-
_new_hash[key] = convert_value(value, conversion: :to_hash)
386-
end
387-
_new_hash
381+
copy = Hash[self]
382+
copy.transform_values! { |v| convert_value_to_hash(v) }
383+
set_defaults(copy)
384+
copy
388385
end
389386

390387
def to_proc
@@ -398,11 +395,7 @@ def convert_key(key)
398395

399396
def convert_value(value, conversion: nil)
400397
if value.is_a? Hash
401-
if conversion == :to_hash
402-
value.to_hash
403-
else
404-
value.nested_under_indifferent_access
405-
end
398+
value.nested_under_indifferent_access
406399
elsif value.is_a?(Array)
407400
if conversion != :assignment || value.frozen?
408401
value = value.dup
@@ -413,6 +406,17 @@ def convert_value(value, conversion: nil)
413406
end
414407
end
415408

409+
def convert_value_to_hash(value)
410+
if value.is_a? Hash
411+
value.to_hash
412+
elsif value.is_a?(Array)
413+
value.map { |e| convert_value_to_hash(e) }
414+
else
415+
value
416+
end
417+
end
418+
419+
416420
def set_defaults(target)
417421
if default_proc
418422
target.default_proc = default_proc.dup

0 commit comments

Comments
 (0)