Skip to content

Commit

Permalink
Refactor prepare_hash
Browse files Browse the repository at this point in the history
  • Loading branch information
sferik committed Mar 14, 2024
1 parent 60e60de commit 10307d9
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions lib/multi_json/convertible_hash_keys.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,9 @@ def stringify_keys(hash)
end

def prepare_hash(hash, &key_modifier)
return hash unless key_modifier

case hash
when Array
hash.map { |value| prepare_hash(value, &key_modifier) }
when Hash
hash.each_with_object({}) do |(key, value), result|
result[yield(key)] = prepare_hash(value, &key_modifier)
end
else
handle_simple_objects(hash)
end
return handle_simple_objects(hash) unless hash.is_a?(Array) || hash.is_a?(Hash)
return handle_array(hash, &key_modifier) if hash.is_a?(Array)
handle_hash(hash, &key_modifier)
end

def handle_simple_objects(obj)
Expand All @@ -35,6 +26,17 @@ def handle_simple_objects(obj)
obj.respond_to?(:to_s) ? obj.to_s : obj
end

def handle_array(array, &key_modifier)
array.map { |value| prepare_hash(value, &key_modifier) }
end

def handle_hash(original_hash, &key_modifier)
original_hash.each_with_object({}) do |(key, value), result|
modified_key = key_modifier.call(key)
result[modified_key] = prepare_hash(value, &key_modifier)
end
end

def simple_object?(obj)
obj.is_a?(String) || obj.is_a?(Numeric) || obj == true || obj == false || obj.nil?
end
Expand Down

0 comments on commit 10307d9

Please sign in to comment.