Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Last active January 19, 2026 18:11
Show Gist options
  • Select an option

  • Save jmbarbone/4ec28bbccf08fd35b7841b721a7dfa08 to your computer and use it in GitHub Desktop.

Select an option

Save jmbarbone/4ec28bbccf08fd35b7841b721a7dfa08 to your computer and use it in GitHub Desktop.
R options validations through active bindings?
# set in options(name = value)
# retrieved in fuj.options$name
# when retrieved, runs getter
fuj.options <- local({
self <- environment()
optenv <- new.env()
active <- function(name, default, getter) {
makeActiveBinding(
name,
local({
default <- default
function(value) {
name <- sprintf("fuj.%s", name)
if (missing(value)) {
getter(getOption(name, default))
} else {
opt <- list(value)
names(opt) <- name
options(opt)
}
}
}),
optenv
)
}
local(envir = optenv, {
active("vap.progress", FALSE, isTRUE)
active("vap.indexed_errors", FALSE, isTRUE)
active("verbose", NULL, \(v) if (is.null(v)) NULL else isTRUE(v))
active("verbose.fill", FALSE, isTRUE)
active(
"verbose.label",
"verbose: ",
function(v) {
v <- as.character(v)
if (length(v) != 1L) {
stop("`fuj.verbose.label` must be a single string.", call. = FALSE)
}
v
}
)
})
optenv
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment