/
float.cr
66 lines (56 loc) · 1.69 KB
/
float.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module Marten
abstract class Schema
module Field
# Represents a float schema field.
class Float < Base
# Returns the maximum value allowed.
getter max_value
# Returns the minimum value allowed.
getter min_value
def initialize(
@id : ::String,
@required : ::Bool = true,
@min_value : Float64? = nil,
@max_value : Float64? = nil
)
end
def deserialize(value) : Float64?
return if empty_value?(value)
case value
when Nil
value
when ::String
Float64.new(value)
when ::Float
value.to_f64
when ::Int
value.to_f64
when ::JSON::Any
deserialize(value.raw)
else
raise_unexpected_field_value(value)
end
end
def serialize(value) : ::String?
value.try(&.to_s)
end
def validate(schema, value)
return if !value.is_a?(Float64)
if !value.finite?
schema.errors.add(id, invalid_error_message(schema), type: :invalid)
return
end
if !min_value.nil? && value < min_value.not_nil!
schema.errors.add(id, I18n.t("marten.schema.field.float.errors.too_small", min_value: min_value))
end
if !max_value.nil? && value > max_value.not_nil!
schema.errors.add(id, I18n.t("marten.schema.field.float.errors.too_big", max_value: max_value))
end
end
private def invalid_error_message(_schema)
I18n.t("marten.schema.field.float.errors.invalid")
end
end
end
end
end