diff options
author | Bobby McDonald <BobbyMcWho@users.noreply.github.com> | 2019-11-18 17:04:37 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-11-18 17:04:37 -0500 |
commit | d5f253963731f7b2ef96ba415ecad22c89e22d28 (patch) | |
tree | f2a772ddfe026f34262d3339f8efa6c351c626d8 /README.md | |
parent | 4f014e7fedad93fa2070166051947070cc8ac01c (diff) | |
parent | 15ea67ef0667546627f9a3cd4fef4457512f5880 (diff) | |
download | hashie-d5f253963731f7b2ef96ba415ecad22c89e22d28.tar.gz |
Merge pull request #499 from michaelherold/permissive-respond-to
Add a PermissiveRespondTo extension for Mashes
Diffstat (limited to 'README.md')
-rw-r--r-- | README.md | 24 |
1 files changed, 24 insertions, 0 deletions
@@ -658,6 +658,30 @@ mash['string_key'] #=> 'string' mash[:string_key] #=> 'string' ``` +### Mash Extension: PermissiveRespondTo + +By default, Mash only states that it responds to built-in methods, affixed methods (e.g. setters, underbangs, etc.), and keys that it currently contains. That means it won't state that it responds to a getter for an unset key, as in the following example: + +```ruby +mash = Hashie::Mash.new(a: 1) +mash.respond_to? :b #=> false +``` + +This means that by default Mash is not a perfect match for use with a SimpleDelegator since the delegator will not forward messages for unset keys to the Mash even though it can handle them. + +In order to have a SimpleDelegator-compatible Mash, you can use the `PermissiveRespondTo` extension to make Mash respond to anything. + +```ruby +class PermissiveMash < Hashie::Mash + include Hashie::Extensions::Mash::PermissiveRespondTo +end + +mash = PermissiveMash.new(a: 1) +mash.respond_to? :b #=> true +``` + +This comes at the cost of approximately 20% performance for initialization and setters and 19KB of permanent memory growth for each such class that you create. + ### Mash Extension: SafeAssignment This extension can be mixed into a Mash to guard the attempted overwriting of methods by property setters. When mixed in, the Mash will raise an `ArgumentError` if you attempt to write a property with the same name as an existing method. |