module Schematics::Coerce

Overview

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

Defined in:

coerce.cr

Constant Summary

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

Class Method Summary

Class Method Detail

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

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


[View source]
def self.coerce(value, target_type : Int64.class) : Int64 | Nil #

[View source]
def self.coerce(value, target_type : Float64.class) : Float64 | Nil #

[View source]
def self.coerce(value, target_type : Bool.class) : Bool | Nil #

[View source]
def self.coerce(value, target_type : String.class) : String | Nil #

[View source]
def self.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)


[View source]
def self.to_float64(value) : Float64 | Nil #

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


[View source]
def self.to_int32(value) : Int32 | Nil #

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


[View source]
def self.to_int64(value) : Int64 | Nil #

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


[View source]
def self.to_string(value) : String | Nil #

Coerce value to String Accepts: Any value with .to_s


[View source]