Module: CMDx::Coercions::Array

Extended by:
Array
Included in:
Array
Defined in:
lib/cmdx/coercions/array.rb

Overview

Coerces to Array. JSON-decodes strings; arrays pass through; objects responding to ‘#to_a` are unwrapped; everything else is wrapped.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Array, 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
# File 'lib/cmdx/coercions/array.rb', line 15

def call(value, options = EMPTY_HASH)
  if value.is_a?(::Array)
    value
  elsif value.is_a?(::String)
    result = JSON.parse(value)
    result.is_a?(::Array) ? result : [value]
  elsif value.respond_to?(:to_a)
    value.to_a
  else
    [value]
  end
rescue JSON::ParserError
  [value]
rescue TypeError
  type = I18nProxy.t("cmdx.types.array")
  Failure.new(I18nProxy.t("cmdx.coercions.into_an", type:))
end