summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/stringify_keys.rb
blob: 13d50bce6fc9b848e0b1a0b80067bccbc7ef5baf (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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!
        StringifyKeys.stringify_keys!(self)
        self
      end

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

      module ClassMethods
        # Stringify all keys recursively within nested
        # hashes and arrays.
        # @api private
        def stringify_keys_recursively!(object)
          case object
          when self.class
            object.stringify_keys!
          when ::Array
            object.each do |i|
              stringify_keys_recursively!(i)
            end
          when ::Hash
            stringify_keys!(object)
          end
        end

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

        # Return a copy of hash with all keys converted
        # to strings.
        # @param [::Hash] hash
        def stringify_keys(hash)
          hash.dup.tap do | new_hash |
            stringify_keys! new_hash
          end
        end
      end

      class << self
        include ClassMethods
      end
    end
  end
end