Class: Dio::Forwarders::StringHashForwarder

Inherits:
BaseForwarder
  • Object
show all
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

Author:

  • [baweaver]

Since:

  • 0.0.3

Constant Summary collapse

NEW_DIVE =

Wrapper for creating a new Forwarder

Since:

  • 0.0.3

-> v { new(v) }

Instance Method Summary collapse

Methods inherited from BaseForwarder

#initialize

Constructor Details

This class inherits a constructor from Dio::Forwarders::BaseForwarder

Instance Method Details

#deconstructArray

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.

Returns:

  • (Array)

Raises:

Since:

  • 0.0.3



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.

Parameters:

  • keys (Array)

    Keys to extract

Returns:

  • (Hash)

Since:

  • 0.0.3



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

#valueAny Also known as: __getobj__

Unwrapped context, aliased afterwards to use Ruby's delegator interface

Returns:

  • (Any)

    Originally wrapped object

Since:

  • 0.0.3



56
57
58
# File 'lib/dio/forwarders/string_hash_forwarder.rb', line 56

def value
  @base_object
end