Skip to content

Instantly share code, notes, and snippets.

@owen2345
Last active June 19, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owen2345/1400e0ec5224a2e842ebd750d402133a to your computer and use it in GitHub Desktop.
Save owen2345/1400e0ec5224a2e842ebd750d402133a to your computer and use it in GitHub Desktop.
Repair numbers converted into string (Rails 4)
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