module Hashie::Extensions::StringifyKeys::ClassMethods

@example Add recursive conversion functions to an object

converter = Object.new.extend(Hashie::Extensions::StringifyKeys::ClassMethods)
converter.stringify_keys(user: { name: 'Ada' }) # => { 'user' => { 'name' => 'Ada' } }

Public Instance Methods

stringify_keys(hash) click to toggle source

Returns a shallow copy of a hash with recursively stringified keys. Nested hashes and arrays are shared with the original and are modified.

@example Copy keys through Hashie's module function

test = { abc: 'def' }
Hashie.stringify_keys(test) # => { 'abc' => 'def' }
test # => { abc: 'def' }

@api public @param [Hash] hash @return [Hash] a shallow copy with stringified keys

# File lib/hashie/extensions/stringify_keys.rb, line 112
def stringify_keys(hash)
  copy = hash.dup
  copy.extend(Hashie::Extensions::StringifyKeys) unless copy.respond_to?(:stringify_keys!)
  copy.tap do |new_hash|
    stringify_keys!(new_hash)
  end
end
stringify_keys!(hash) click to toggle source

Converts all keys in a hash recursively to strings, in place.

@example Convert keys through Hashie's module function

test = { abc: 'def' }
Hashie.stringify_keys!(test)
test # => { 'abc' => 'def' }

@api public @param [Hash] hash @return [Hash] the passed hash with stringified keys

# File lib/hashie/extensions/stringify_keys.rb, line 92
def stringify_keys!(hash)
  hash.extend(Hashie::Extensions::StringifyKeys) unless hash.respond_to?(:stringify_keys!)
  hash.keys.each do |k| # rubocop:disable Performance/HashEachMethods
    stringify_keys_recursively!(hash[k])
    hash[k.to_s] = hash.delete(k)
  end
  hash
end
stringify_keys_recursively!(object) click to toggle source

Stringify all keys recursively within nested hashes and arrays. @api private

# File lib/hashie/extensions/stringify_keys.rb, line 71
def stringify_keys_recursively!(object)
  case object
  when ::Array
    object.each do |i|
      stringify_keys_recursively!(i)
    end
  when ::Hash
    stringify_keys!(object)
  end
end