Module: Hashie::Extensions::StrictKeyAccess

Defined in:
lib/hashie/extensions/strict_key_access.rb

Overview

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".

Defined Under Namespace

Classes: DefaultError

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

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"


48
49
50
# File 'lib/hashie/extensions/strict_key_access.rb', line 48

def [](key)
  fetch(key)
end

#default(_ = nil) ⇒ Object

Raises:



52
53
54
# File 'lib/hashie/extensions/strict_key_access.rb', line 52

def default(_ = nil)
  raise DefaultError
end

#default=(_) ⇒ Object

Raises:



56
57
58
# File 'lib/hashie/extensions/strict_key_access.rb', line 56

def default=(_)
  raise DefaultError
end

#default_procObject

Raises:



60
61
62
# File 'lib/hashie/extensions/strict_key_access.rb', line 60

def default_proc
  raise DefaultError
end

#default_proc=(_) ⇒ Object

Raises:



64
65
66
# File 'lib/hashie/extensions/strict_key_access.rb', line 64

def default_proc=(_)
  raise DefaultError
end

#key(value) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/hashie/extensions/strict_key_access.rb', line 68

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