summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/mash/keep_original_keys.rb
blob: 91b9b445d677e968f5e2505d9e379cd21b510c62 (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
module Hashie
  module Extensions
    module Mash
      # Overrides the indifferent access of a Mash to keep keys in the
      # original format given to the Mash.
      #
      # @example
      #   class KeepingMash < Hashie::Mash
      #     include Hashie::Extensions::Mash::KeepOriginalKeys
      #   end
      #
      #   mash = KeepingMash.new(:symbol_key => :symbol, 'string_key' => 'string')
      #   mash.to_hash  #=> { :symbol_key => :symbol, 'string_key' => 'string' }
      #   mash['string_key'] == mash[:string_key]  #=> true
      #   mash[:symbol_key] == mash['symbol_key']  #=> true
      module KeepOriginalKeys
        def self.included(descendant)
          raise ArgumentError, "#{descendant} is not a kind of Hashie::Mash" unless descendant <= Hashie::Mash
        end

        private

        # Converts the key when necessary to access the correct Mash key.
        #
        # @param [Object, String, Symbol] key the key to access.
        # @return [Object] the value assigned to the key.
        def convert_key(key)
          if regular_key?(key)
            key
          elsif (converted_key = __convert(key)) && regular_key?(converted_key)
            converted_key
          else
            key
          end
        end

        # Converts symbol/string keys to their alternative formats, but leaves
        # other keys alone.
        #
        # @param [Object, String, Symbol] key the key to convert.
        # @return [Object, String, Symbol] the converted key.
        def __convert(key)
          case key
          when Symbol then key.to_s
          when String then key.to_sym
          else key
          end
        end
      end
    end
  end
end