Module: CMDx::Coercions::Hash

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

Overview

Coerces various input types into Hash objects

Supports conversion from:

  • Nil values (converted to empty Hash)

  • Hash objects (returned as-is)

  • Array objects (converted using Hash)

  • JSON strings starting with “{” (parsed into Hash)

  • Other types raise CoercionError

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ Hash

Coerces a value into a Hash

Examples:

Coerce from existing Hash

Hash.call({a: 1, b: 2}) # => {a: 1, b: 2}

Coerce from Array

Hash.call([:a, 1, :b, 2]) # => {a: 1, b: 2}

Coerce from JSON string

Hash.call('{"key": "value"}') # => {"key" => "value"}

Parameters:

  • value (Object)

    The value to coerce

  • options (Hash) (defaults to: {})

    Additional options (currently unused)

Options Hash (options):

  • :strict (Symbol)

    Whether to enforce strict conversion

Returns:

  • (Hash)

    The coerced hash value

Raises:



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cmdx/coercions/hash.rb', line 35

def call(value, options = {})
  if value.nil?
    {}
  elsif value.is_a?(::Hash)
    value
  elsif value.is_a?(::Array)
    ::Hash[*value]
  elsif value.is_a?(::String) && value.start_with?("{")
    JSON.parse(value)
  elsif value.respond_to?(:to_h)
    value.to_h
  else
    raise_coercion_error!
  end
rescue ArgumentError, TypeError, JSON::ParserError
  raise_coercion_error!
end