Module: CMDx::Coercions::Array

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

Overview

Converts various input types to Array format

Handles conversion from strings that look like JSON arrays and other values that can be wrapped in an array using Ruby’s Array() method.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Array

Converts a value to an Array

Examples:

Convert a JSON-like string to an array

Array.call("[1, 2, 3]") # => [1, 2, 3]

Convert other values using Array()

Array.call("hello")     # => ["hello"]
Array.call(42)          # => [42]
Array.call(nil)         # => []

Handle invalid JSON-like strings

Array.call("[not json") # => raises CoercionError

Parameters:

  • value (Object)

    The value to convert to an array

  • options (Hash) (defaults to: EMPTY_HASH)

    Optional configuration parameters (currently unused)

Options Hash (options):

  • :unused (Object)

    Currently no options are used

Returns:

  • (Array)

    The converted array value

Raises:

  • (CoercionError)

    If the value cannot be converted to an array

Rbs:

  • (untyped value, ?Hash[Symbol, untyped] options) -> Array



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cmdx/coercions/array.rb', line 33

def call(value, options = EMPTY_HASH)
  if value.is_a?(::String) && (
    value.start_with?("[") ||
    value.strip == "null"
  )
    JSON.parse(value) || []
  else
    Utils::Wrap.array(value)
  end
rescue JSON::ParserError
  type = Locale.t("cmdx.types.array")
  raise CoercionError, Locale.t("cmdx.coercions.into_an", type:)
end