Sha256: b7aafa618ff7b8f1e985edab7e3edb08923119b9f339bf13c877ea92823144fb

Contents?: true

Size: 1.2 KB

Versions: 6

Compression:

Stored size: 1.2 KB

Contents

module Crystal
  class HashWithStringifyKeys < Hash
    def initialize(constructor = {})
      if constructor.is_a?(Hash)
        super()
        update(constructor).stringify_keys!
      else
        super(constructor)
      end
    end

    # https://github.com/intridea/hashie/blob/master/lib/hashie/extensions/key_conversion.rb

    # Convert all keys in the hash to strings.
    # @example
    #   test = {:abc => 'def'}
    #   test.stringify_keys!
    #   test # => {'abc' => 'def'}
    def stringify_keys!
      keys.each do |k|
        stringify_keys_recursively!(self[k])
        self[k.to_s] = self.delete(k)
      end
      self
    end

    # Return a new hash with all keys converted
    # to strings.
    def stringify_keys
      dup.stringify_keys!
    end

    protected

    # Stringify all keys recursively within nested
    # hashes and arrays.
    def stringify_keys_recursively!(object)
      if self.class === object
        object.stringify_keys!
      elsif ::Array === object
        object.each do |i|
          stringify_keys_recursively!(i)
        end
        object
      elsif object.respond_to?(:stringify_keys!)
        object.stringify_keys!
      else
        object
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
crystalmeta-1.0.0 lib/crystal/hash_with_stringify_keys.rb
crystalmeta-0.9.4 lib/crystal/hash_with_stringify_keys.rb
crystalmeta-0.9.3 lib/crystal/hash_with_stringify_keys.rb
crystalmeta-0.9.2 lib/crystal/hash_with_stringify_keys.rb
crystalmeta-0.9.1 lib/crystal/hash_with_stringify_keys.rb
crystalmeta-0.9.0 lib/crystal/hash_with_stringify_keys.rb