Module: Surrealist::TypeHelper

Defined in:
lib/surrealist/type_helper.rb

Overview

Service class for type checking

Constant Summary collapse

DRY_TYPE_CLASS =

Dry-types class matcher

/Dry::Types/.freeze

Class Method Summary collapse

Class Method Details

.coerce(value, type) ⇒ any

Coerces value is it should be coerced

Parameters:

  • value (any)

    value that will be coerced

  • type (Class)

    class representing data type

Returns:

  • (any)

    coerced value



35
36
37
38
39
40
# File 'lib/surrealist/type_helper.rb', line 35

def coerce(value, type)
  return value unless dry_type?(type)
  return value if type.try(value).input == value

  type[value]
end

.valid_type?(value, type) ⇒ boolean

Checks if value returned from a method is an instance of type class specified in schema or NilClass.

Parameters:

  • value (any)

    value returned from a method.

  • type (Class)

    class representing data type.

Returns:

  • (boolean)


17
18
19
20
21
22
23
24
25
26
27
# File 'lib/surrealist/type_helper.rb', line 17

def valid_type?(value, type)
  return true if type == Any

  if type == Bool
    Surrealist::Carrier::BOOLEANS.include?(value)
  elsif defined?(Dry::Types) && dry_type?(type)
    type.try(value).success?
  else
    value.nil? || value.is_a?(type)
  end
end