Sha256: cce08b395636086cf98fac882172ad1fc1ec5b6d28a73e1f241f54822110d71f
Contents?: true
Size: 1.17 KB
Versions: 2
Compression:
Stored size: 1.17 KB
Contents
module ChartMogul module Utils class HashSnakeCaser # # Recursively converts CamelCase and camelBack JSON-style hash keys to # Rubyish snake_case, suitable for use during instantiation of Ruby # model attributes. # def initialize(hash) @hash = hash end def to_snake_keys(value = @hash) case value when Array value.map { |v| to_snake_keys(v) } when Hash snake_hash(value) else value end end private def snake_hash(value) Hash[value.map { |k, v| [underscore_key(k), to_snake_keys(v)] }] end def underscore_key(k) if k.instance_of?(Symbol) underscore(k.to_s).to_sym elsif k.instance_of?(String) underscore(k) else k # Can't snakify anything except strings and symbols end end def underscore(string) string.gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
chartmogul-ruby-1.1.4 | lib/chartmogul/utils/hash_snake_caser.rb |
chartmogul-ruby-1.1.2 | lib/chartmogul/utils/hash_snake_caser.rb |