Module: CMDx::Coercions::Hash

Extended by:
Hash
Included in:
Hash
Defined in:
lib/cmdx/coercions/hash.rb

Overview

Coerces to Hash. ‘nil` becomes `{}`; strings are JSON-decoded (and must decode to a Hash); `#to_hash`/`#to_h` are used as fallbacks.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Hash, Coercions::Failure

Parameters:

  • value (Object)
  • options (Hash{Symbol => Object}) (defaults to: EMPTY_HASH)

Options Hash (options):

  • reserved (Object)

    for future per-coercion configuration (currently ignored)

Returns:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cmdx/coercions/hash.rb', line 15

def call(value, options = EMPTY_HASH)
  if value.nil?
    {}
  elsif value.is_a?(::Hash)
    value
  elsif value.is_a?(::String)
    result = JSON.parse(value)
    result.is_a?(::Hash) ? result : coercion_failure
  elsif value.respond_to?(:to_hash)
    value.to_hash
  elsif value.respond_to?(:to_h)
    value.to_h
  else
    coercion_failure
  end
rescue ArgumentError, TypeError, JSON::ParserError
  coercion_failure
end