Sha256: 1aa306dc0bd0ee48935043302ced9d58f7c78debd6c7d7abd711b264d2090475

Contents?: true

Size: 1.82 KB

Versions: 5

Compression:

Stored size: 1.82 KB

Contents

module Hashie
  module Extensions
    # SRP: This extension will fail an error whenever a key is accessed
    #   that does not exist in the hash.
    #
    #   EXAMPLE:
    #
    #     class StrictKeyAccessHash < Hash
    #       include Hashie::Extensions::StrictKeyAccess
    #     end
    #
    #     >> hash = StrictKeyAccessHash[foo: "bar"]
    #     => {:foo=>"bar"}
    #     >> hash[:foo]
    #     => "bar"
    #     >> hash[:cow]
    #       KeyError: key not found: :cow
    #
    # NOTE: For googlers coming from Python to Ruby, this extension makes a Hash
    # behave more like a "Dictionary".
    #
    module StrictKeyAccess
      class DefaultError < StandardError
        def initialize
          super('Setting or using a default with Hashie::Extensions::StrictKeyAccess'\
                ' does not make sense'
          )
        end
      end

      # NOTE: Defaults don't make any sense with a StrictKeyAccess.
      # NOTE: When key lookup fails a KeyError is raised.
      #
      # Normal:
      #
      #     >> a = Hash.new(123)
      #     => {}
      #     >> a["noes"]
      #     => 123
      #
      # With StrictKeyAccess:
      #
      #     >> a = StrictKeyAccessHash.new(123)
      #     => {}
      #     >> a["noes"]
      #       KeyError: key not found: "noes"
      #
      def [](key)
        fetch(key)
      end

      def default(_ = nil)
        raise DefaultError
      end

      def default=(_)
        raise DefaultError
      end

      def default_proc
        raise DefaultError
      end

      def default_proc=(_)
        raise DefaultError
      end

      def key(value)
        super.tap do |result|
          if result.nil? && (!key?(result) || self[result] != value)
            raise KeyError, "key not found with value of #{value.inspect}"
          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/strict_key_access.rb
hashie-5.0.0 lib/hashie/extensions/strict_key_access.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/hashie-4.1.0/lib/hashie/extensions/strict_key_access.rb
hashie-4.1.0 lib/hashie/extensions/strict_key_access.rb
hashie-4.0.0 lib/hashie/extensions/strict_key_access.rb