Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def convert_hash_keys(value)
- return value if (not value.is_a?(Array) and not value.is_a?(Hash))
- result = value.inject({}) do |new, (key, value)|
- new[to_snake_case(key.to_s).to_sym] = convert_hash_keys(value)
- new
- end
- result
- end
- def to_snake_case(string)
- string.gsub(/::/, '/').
- gsub(/([A-Z]+)([A-Z][a-z])/,'1_2').
- gsub(/([a-zd])([A-Z])/,'1_2').
- tr("-", "_").
- downcase
- end
- hash = {:HashKey => {:NestedHashKey => [{:Key => "value"}]}}
- convert_hash_keys(hash)
- # => {:hash_key => {:nested_hash_key => [{:key => "value"}]}}
- def underscore_key(k)
- k.to_s.underscore.to_sym
- # Or, if you're not in Rails:
- # to_snake_case(k.to_s).to_sym
- end
- def convert_hash_keys(value)
- case value
- when Array
- value.map { |v| convert_hash_keys(v) }
- # or `value.map(&method(:convert_hash_keys))`
- when Hash
- Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
- else
- value
- end
- end
- hash = { camelCase: 'value1', changeMe: 'value2' }
- hash.transform_keys { |key| key.to_s.underscore }
- # => { "camel_case" => "value1", "change_me" => "value2" }
- hash = { camelCase: 'value1', changeMe: { hereToo: { andMe: 'thanks' } } }
- hash.deep_transform_keys { |key| key.to_s.underscore }
- # => {"camel_case"=>"value1", "change_me"=>{"here_too"=>{"and_me"=>"thanks"}}}
- hash.deep_transform_keys! do |key|
- k = key.to_s.downcase rescue key
- k.to_sym rescue key
- end
Add Comment
Please, Sign In to add comment