Module: Hashie::Extensions::StringifyKeys::ClassMethods

Included in:
Hashie, Hashie::Extensions::StringifyKeys
Defined in:
lib/hashie/extensions/stringify_keys.rb

Instance Method Summary collapse

Instance Method Details

#stringify_keys(hash) ⇒ Object

Return a copy of hash with all keys converted to strings.

Parameters:

  • hash (::Hash)


57
58
59
60
61
62
63
# File 'lib/hashie/extensions/stringify_keys.rb', line 57

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) ⇒ Object

Convert all keys in the hash to strings.

Examples:

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

Parameters:

  • hash (::Hash)


45
46
47
48
49
50
51
52
# File 'lib/hashie/extensions/stringify_keys.rb', line 45

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) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Stringify all keys recursively within nested hashes and arrays.



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hashie/extensions/stringify_keys.rb', line 25

def stringify_keys_recursively!(object)
  case object
  when self.class
    stringify_keys!(object)
  when ::Array
    object.each do |i|
      stringify_keys_recursively!(i)
    end
  when ::Hash
    stringify_keys!(object)
  end
end