Sha256: b6727585afb904bbe8f61fc91ed2ad5f00535a82cfcf2a1fa1d4cd7d43e493d8

Contents?: true

Size: 1.12 KB

Versions: 10

Compression:

Stored size: 1.12 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

10 entries across 10 versions & 1 rubygems

Version Path
chartmogul-ruby-1.1.3 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.1.1 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.1.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.0.2 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.0.1 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.0.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-0.1.4 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-0.1.3 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-0.1.2 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-0.1.1 lib/chartmogul/utils/hash_snake_caser.rb