s <- Schema(list(check_my_attr = 1L))
s@errors # doesn't recognise rule
s <- add_rule(
obj = s,
name = "check_my_attr",
validator_fn = function(data_field, schema_field, ...) {
if (attr(data_field, "my_attr") != schema_field) {
list(error = "Data doesn't match schema 'my_attr'.")
}
},
schema_fn = function(schema_field, ...) {
if (!is.character(schema_field) || length(schema_field) != 1L) {
"Must be length 1 character"
}
},
rule_type = "validate"
)
# rule recognised and schema automatically re-validated
s@errors
# validation works with the new rule
s@schema$check_my_attr <- "Hi"
Validator(structure(1L, my_attr = "Hi"), s)@valid # TRUE
# schema cross rules invalidate when constituent rules are invalid
s <- add_cross_rule(
obj = s,
name = "min_and_max_val_add_to_10",
rule_names = c("min_val", "max_val"),
cross_fn = function(schema_field, ...) {
if (schema_field$min_val + schema_field$max_val == 10) {
"`min_val` and `max_val` cannot add to 10."
}
}
)
s@schema <- list(min_val = 2, max_val = 8)
s@errors # cross rule error
r <- Registry()
r <- add_type_rule(r, "my_type", function(x) {
inherits(x, "my_type")
})
s <- Schema(list(type = "my_type"), registry = r)
s@valid # TRUE
Validator(structure(1, class = "my_type"), s)@valid # TRUE
r <- add_coerce_rule(r, "my_type", function(x) {
structure(x, class = c("my_type", class(x)))
})
s <- Schema(list(coerce = "my_type"), registry = r)
v <- Validator(1, s)
class(v@data) # "my_type" "numeric"
# environments are copied, so original registry is not modified
r <- Registry()
r2 <- add_type_rule(r, "my_type", function(x) x)
identical(r@type_map, r2@type_map) # FALSE
Run the code above in your browser using DataLab