module

Schematics::Coerce

Type coercion module for converting values between compatible types

Coercion is opt-in per field using coerce: true:

class User < Schematics::Model
  field age, Int32, coerce: true   # "25" -> 25
  field active, Bool, coerce: true # "true" -> true
end

Constants

FALSE_VALUES = ["0", "false", "no", "off", "f", "n"] of ::String
TRUE_VALUES = ["1", "true", "yes", "on", "t", "y"] of ::String

Class methods

coerce(value, target_type : Int32.class) : Int32 | Nil

Generic coercion dispatcher based on target type Used by macros to coerce JSON::Any values

Source
coerce(value, target_type : Int64.class) : Int64 | Nil
Source
coerce(value, target_type : Float64.class) : Float64 | Nil
Source
coerce(value, target_type : Bool.class) : Bool | Nil
Source
coerce(value, target_type : String.class) : String | Nil
Source
to_bool(value) : Bool | Nil

Coerce value to Bool Accepts: Bool, Int32/Int64 (0 or 1), String (true/false/yes/no/on/off/1/0)

Source
to_float64(value) : Float64 | Nil

Coerce value to Float64 Accepts: Float64, Int32, Int64, String (numeric)

Source
to_int32(value) : Int32 | Nil

Coerce value to Int32 Accepts: Int32, Int64, Float64 (if whole number), String (numeric), Bool

Source
to_int64(value) : Int64 | Nil

Coerce value to Int64 Accepts: Int32, Int64, Float64 (if whole number), String (numeric), Bool

Source
to_string(value) : String | Nil

Coerce value to String Accepts: Any value with .to_s

Source