Module: Hashie::Extensions::Mash::PermissiveRespondTo

Defined in:
lib/hashie/extensions/mash/permissive_respond_to.rb

Overview

Allow a Mash to properly respond to everything

By default, Mashes only say they respond to methods for keys that exist in their key set or any of the affix methods (e.g. setter, underbang, etc.). This causes issues when you try to use them within a SimpleDelegator or bind to a method for a key that is unset.

This extension allows a Mash to properly respond to respond_to? and method for keys that have not yet been set. This enables full compatibility with SimpleDelegator and thunk-oriented programming.

There is a trade-off with this extension: it will run slower than a regular Mash; insertions and initializations with keys run approximately 20% slower and cost approximately 19KB of memory per class that you make permissive.

Examples:

Make a new, permissively responding Mash subclass

class PermissiveMash < Hashie::Mash
  include Hashie::Extensions::Mash::PermissiveRespondTo
end

mash = PermissiveMash.new(a: 1)
mash.respond_to? :b  #=> true

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The Ruby hook for behavior when including the module

Returns:

  • void



34
35
36
37
# File 'lib/hashie/extensions/mash/permissive_respond_to.rb', line 34

def self.included(base)
  base.instance_variable_set :@_method_cache, base.instance_methods
  base.define_singleton_method(:method_cache) { @_method_cache }
end

Instance Method Details

#respond_to_missing?(_method_name, _include_private = false) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The Ruby hook for determining what messages a class might respond to

Returns:

  • (Boolean)


43
44
45
# File 'lib/hashie/extensions/mash/permissive_respond_to.rb', line 43

def respond_to_missing?(_method_name, _include_private = false)
  true
end