Sha256: 41a69dabefa988084bf1d76324a71a9a5decf77441503ebee6cdc63769e2cd58

Contents?: true

Size: 1.34 KB

Versions: 16

Compression:

Stored size: 1.34 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, immutable_keys: [])
        @hash = hash
        @immutable_keys = immutable_keys
      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), immutable_check(k, v)] }]
      end

      def immutable_check(k,v)
        return v if @immutable_keys.include?(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

16 entries across 16 versions & 1 rubygems

Version Path
chartmogul-ruby-4.4.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-4.3.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-4.2.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-4.1.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-4.0.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.3.1 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.3.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.2.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.1.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.0.2 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-3.0.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-2.9.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-2.1.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-2.0.0 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.7.3 lib/chartmogul/utils/hash_snake_caser.rb
chartmogul-ruby-1.7.2 lib/chartmogul/utils/hash_snake_caser.rb