Last active
June 19, 2020 15:21
-
-
Save owen2345/1400e0ec5224a2e842ebd750d402133a to your computer and use it in GitHub Desktop.
Repair numbers converted into string (Rails 4)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
repair_nested_params({id: '11', age: '25'}) # Sample | |
def repair_nested_params(obj) | |
obj.each { |key, value| obj[key] = parse_value(value) } | |
end | |
def parse_value(value) | |
return repair_nested_params(value) if value.is_a?(Hash) | |
return value.map(&method(:parse_value)) if value.is_a?(Array) | |
return value unless value.is_a?(String) | |
is_numeric = value.match?(/\A[-+]?\d*\.?\d+\z/) | |
return value unless is_numeric | |
(value.to_f % 1).positive? ? value.to_f : value.to_i | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment