forked from RConsortium/S7
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid.R
More file actions
54 lines (47 loc) · 1.54 KB
/
valid.R
File metadata and controls
54 lines (47 loc) · 1.54 KB
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
#' Validation of R7 objects
#'
#' [validate()] calls the validation of an R7 object. This is done
#' automatically when creating new objects (at the end of [new_object]) and
#' when setting any property.
#'
#' [valid_eventually()] disables validation of properties, runs a function on
#' the object, then validates the object.
#'
#' [valid_implicitly()] does the same but does not validate the object at the end.
#'
#' [valid_implicitly()] should only be used rarely in performance critical code
#' where you are certain a sequence of operations cannot produce an invalid
#' object.
#' @param object An R7 object
#' @param fun A function to call on the object before validation.
validate <- function(object) {
if (!is.null(attr(object, ".should_validate"))) {
return(invisible(object))
}
obj_class <- object_class(object)
validator <- property(obj_class, "validator")
errors <- validator(object)
if (length(errors) > 0) {
msg <- sprintf("Invalid <%s> object:\n%s", obj_class@name, paste0("- ", errors, collapse = "\n"))
stop(msg, call. = FALSE)
}
invisible(object)
}
#' @rdname validate
#' @export
valid_eventually <- function(object, fun) {
old <- attr(object, ".should_validate")
attr(object, ".should_validate") <- FALSE
out <- fun(object)
attr(out, ".should_validate") <- old
validate(out)
}
#' @rdname validate
#' @export
valid_implicitly <- function(object, fun) {
old <- attr(object, ".should_validate")
attr(object, ".should_validate") <- FALSE
out <- fun(object)
attr(out, ".should_validate") <- old
invisible(out)
}