Class: Dio::Forwarders::StringHashForwarder
- Inherits:
-
BaseForwarder
- Object
- Delegator
- BaseForwarder
- Dio::Forwarders::StringHashForwarder
- Defined in:
- lib/dio/forwarders/string_hash_forwarder.rb
Overview
Pattern Matching relies on Symbol keys for Hash matching, but a significant number of Ruby Hashes are keyed with Strings. This forwarder addresses that issue by transforming String keys into Symbols for the sake of matching against them:
Dio.string_hash({ 'a' => 1 }) in { a: 1 }
# => true
Constant Summary collapse
- NEW_DIVE =
Wrapper for creating a new Forwarder
-> v { new(v) }
Instance Method Summary collapse
-
#deconstruct ⇒ Array
If an Array is provided from nested values we may want to match against it as well.
-
#deconstruct_keys(keys) ⇒ Hash
Extracts keys from a Hash by treating the provided keys like Strings.
-
#value ⇒ Any
(also: #__getobj__)
Unwrapped context, aliased afterwards to use Ruby's delegator interface.
Methods inherited from BaseForwarder
Constructor Details
This class inherits a constructor from Dio::Forwarders::BaseForwarder
Instance Method Details
#deconstruct ⇒ Array
If an Array is provided from nested values we may want to match against it as well. Wrap the values in new forwarders to accomodate this.
31 32 33 34 35 36 |
# File 'lib/dio/forwarders/string_hash_forwarder.rb', line 31 def deconstruct return @base_object.map(&NEW_DIVE) if @base_object.is_a?(Array) # Debating on this one raise Dio::Errors::NoDeconstructionMethod end |
#deconstruct_keys(keys) ⇒ Hash
Extracts keys from a Hash by treating the provided keys like Strings. Return the base object with keys transformed to Symbols to accomodate pattern matching features.
46 47 48 49 50 |
# File 'lib/dio/forwarders/string_hash_forwarder.rb', line 46 def deconstruct_keys(keys) @base_object .slice(*keys.map(&:to_s)) .to_h { |k, v| [k.to_sym, NEW_DIVE[v]] } end |
#value ⇒ Any Also known as: __getobj__
Unwrapped context, aliased afterwards to use Ruby's delegator interface
56 57 58 |
# File 'lib/dio/forwarders/string_hash_forwarder.rb', line 56 def value @base_object end |