Sha256: ef138227c68219456d1c79acb73f8dc1d52fb5e7bc5ea1993268c730c75bb812

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

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

1 entries across 1 versions & 1 rubygems

Version Path
chartmogul-ruby-1.1.5 lib/chartmogul/utils/hash_snake_caser.rb