Sha256: 067376269df1ee0bf3a0aca5d9bdb16603ae97086c6cc0436c4bc1fa954d9cb7

Contents?: true

Size: 1.69 KB

Versions: 5

Compression:

Stored size: 1.69 KB

Contents

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)
          error_message = "#{descendant} is not a kind of Hashie::Mash"
          raise ArgumentError, error_message 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

Version data entries

5 entries across 5 versions & 3 rubygems

Version Path
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/hashie-5.0.0/lib/hashie/extensions/mash/keep_original_keys.rb
hashie-5.0.0 lib/hashie/extensions/mash/keep_original_keys.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/hashie-4.1.0/lib/hashie/extensions/mash/keep_original_keys.rb
hashie-4.1.0 lib/hashie/extensions/mash/keep_original_keys.rb
hashie-4.0.0 lib/hashie/extensions/mash/keep_original_keys.rb