Guest User

Untitled

a guest
Jan 24th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. def convert_hash_keys(value)
  2. return value if (not value.is_a?(Array) and not value.is_a?(Hash))
  3. result = value.inject({}) do |new, (key, value)|
  4. new[to_snake_case(key.to_s).to_sym] = convert_hash_keys(value)
  5. new
  6. end
  7. result
  8. end
  9.  
  10. def to_snake_case(string)
  11. string.gsub(/::/, '/').
  12. gsub(/([A-Z]+)([A-Z][a-z])/,'1_2').
  13. gsub(/([a-zd])([A-Z])/,'1_2').
  14. tr("-", "_").
  15. downcase
  16. end
  17.  
  18. hash = {:HashKey => {:NestedHashKey => [{:Key => "value"}]}}
  19.  
  20. convert_hash_keys(hash)
  21. # => {:hash_key => {:nested_hash_key => [{:key => "value"}]}}
  22.  
  23. def underscore_key(k)
  24. k.to_s.underscore.to_sym
  25. # Or, if you're not in Rails:
  26. # to_snake_case(k.to_s).to_sym
  27. end
  28.  
  29. def convert_hash_keys(value)
  30. case value
  31. when Array
  32. value.map { |v| convert_hash_keys(v) }
  33. # or `value.map(&method(:convert_hash_keys))`
  34. when Hash
  35. Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
  36. else
  37. value
  38. end
  39. end
  40.  
  41. hash = { camelCase: 'value1', changeMe: 'value2' }
  42.  
  43. hash.transform_keys { |key| key.to_s.underscore }
  44. # => { "camel_case" => "value1", "change_me" => "value2" }
  45.  
  46. hash = { camelCase: 'value1', changeMe: { hereToo: { andMe: 'thanks' } } }
  47.  
  48. hash.deep_transform_keys { |key| key.to_s.underscore }
  49. # => {"camel_case"=>"value1", "change_me"=>{"here_too"=>{"and_me"=>"thanks"}}}
  50.  
  51. hash.deep_transform_keys! do |key|
  52. k = key.to_s.downcase rescue key
  53. k.to_sym rescue key
  54. end
Add Comment
Please, Sign In to add comment