Sha256: 05acad3b9bf0ebaa02cab889d708e0a06aed783f892eb034f802dbf722a7bc04

Contents?: true

Size: 1.16 KB

Versions: 9

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

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

9 entries across 9 versions & 1 rubygems

Version Path
chartmogul-ruby-1.7.1 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.9 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.8 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.7 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.6 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.4 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.3 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.2 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.6.1 lib/chartmogul/utils/hash_snake_caser.rb