module Hashie::Extensions::Mash::StrictKeyAccess
Overrides Mash’s default behavior of returning nil for keys that aren’t set, raising a KeyError instead.
Unlike Hashie::Extensions::StrictKeyAccess, this extension is aware of Mash’s special suffixed methods (e.g. +?+, +!+, _ and +=+) so that they continue to work as expected instead of always raising.
Because nested Hashes are converted into instances of self.class, this extension is automatically applied to any nested Mash as well.
@example
class StrictMash < Hashie::Mash include Hashie::Extensions::Mash::StrictKeyAccess end mash = StrictMash.new(name: 'Bob') mash.name #=> 'Bob' expect { mash.age }.to raise_error(KeyError, 'key not found: `age`') mash.name? #=> true mash.age? #=> false mash.address!.city = 'Springfield' mash.address.city #=> 'Springfield'
@api public
Public Class Methods
included(descendant)
click to toggle source
Hook for being included in a class
@api private @return [void] @raise [ArgumentError] when the base class isn’t a Mash
# File lib/hashie/extensions/mash/strict_key_access.rb, line 38 def self.included(descendant) error_message = "#{descendant} is not a kind of Hashie::Mash" raise ArgumentError, error_message unless descendant <= Hashie::Mash end
Public Instance Methods
method_missing(method_name, *args, &blk)
click to toggle source
@api private
Calls superclass method
# File lib/hashie/extensions/mash/strict_key_access.rb, line 44 def method_missing(method_name, *args, &blk) return super if key?(method_name) name, suffix = method_name_and_suffix(method_name) raise KeyError, "key not found: `#{name}`" if !key?(name) && !suffix super end
respond_to_missing?(method_name, *args)
click to toggle source
@api private
Calls superclass method
# File lib/hashie/extensions/mash/strict_key_access.rb, line 54 def respond_to_missing?(method_name, *args) return true if key?(method_name) _, suffix = method_name_and_suffix(method_name) return false unless suffix super end