summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/symbolize_keys.rb
blob: d1da9cb83f4fba5f2ee91e58d171dd13e3487e23 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module Hashie
  module Extensions
    module SymbolizeKeys
      # Convert all keys in the hash to symbols.
      #
      # @example
      #   test = {'abc' => 'def'}
      #   test.symbolize_keys!
      #   test # => {:abc => 'def'}
      def symbolize_keys!
        SymbolizeKeys.symbolize_keys!(self)
        self
      end

      # Return a new hash with all keys converted
      # to symbols.
      def symbolize_keys
        SymbolizeKeys.symbolize_keys(self)
      end

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

        # Convert all keys in hash to symbols.
        #
        # @param [Hash] hash
        # @example
        #   test = {'abc' => 'def'}
        #   Hashie.symbolize_keys! test
        #   test # => {:abc => 'def'}
        def symbolize_keys!(hash)
          hash.extend(Hashie::Extensions::SymbolizeKeys) unless hash.respond_to?(:symbolize_keys!)
          hash.keys.each do |k| # rubocop:disable Performance/HashEachMethods
            symbolize_keys_recursively!(hash[k])
            hash[convert_key(k)] = hash.delete(k)
          end
          hash
        end

        # Return a copy of hash with all keys converted
        # to symbols.
        # @param [::Hash] hash
        def symbolize_keys(hash)
          copy = hash.dup
          copy.extend(Hashie::Extensions::SymbolizeKeys) unless copy.respond_to?(:symbolize_keys!)
          copy.tap do |new_hash|
            symbolize_keys!(new_hash)
          end
        end

        private

        # Converts a key to a symbol, if possible
        #
        # @api private
        # @param [<K>] key the key to attempt convert to a symbol
        # @return [Symbol, K]
        def convert_key(key)
          key.respond_to?(:to_sym) ? key.to_sym : key
        end
      end

      class << self
        include ClassMethods
      end
    end
  end
end