summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/stringify_keys.rb
blob: fe00951f9e5a004e51b1e71617b0b8e134c643ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
module Hashie
  module Extensions
    module StringifyKeys
      # 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] = 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
end