From d4306269079278b446840c706687d265072190bd Mon Sep 17 00:00:00 2001 From: Maximilian Held Date: Mon, 15 Jul 2024 17:52:12 +0200 Subject: [PATCH] add local options helper --- DESCRIPTION | 7 ++++--- NAMESPACE | 1 + R/options.R | 23 +++++++++++++++++++++++ tests/testthat/test-options.R | 8 ++++++++ 4 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 R/options.R create mode 100644 tests/testthat/test-options.R diff --git a/DESCRIPTION b/DESCRIPTION index 000d8a7..56331d8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -27,14 +27,15 @@ Roxygen: list(markdown = TRUE) Imports: cli, fs, + options, purrr, rlang, - usethis + usethis, + withr Suggests: rstudioapi, shinytest2, - testthat (>= 3.0.0), - withr + testthat (>= 3.0.0) Config/testthat/edition: 3 Config/testthat/parallel: true Config/Needs/website: rmarkdown diff --git a/NAMESPACE b/NAMESPACE index fb641fe..c4af25c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand export(is_installed2) +export(opt_set_local2) export(source_pef) export(transform_with_generated) export(use_ex_file) diff --git a/R/options.R b/R/options.R new file mode 100644 index 0000000..74a76a3 --- /dev/null +++ b/R/options.R @@ -0,0 +1,23 @@ +#' Helper to locally set options +#' +#' Combines options from [options] with [withr]. +#' Same as [options::opt_set_local], except based on [withr::defer] and friends. +#' +#' @param x An option name. +#' @inheritParams options::opt_set +#' @inheritParams withr::defer +#' @keywords options helper +#' @export +opt_set_local2 <- function(x, + value, + envir = parent.frame(), + priority = c("first", "last")) { + old <- options::opt_set(x = x, value = value, env = envir) + # cannot just extend withr::local_ here, + # because it has slightly different semantics + withr::defer( + options::opt_set(x, old, env = envir), + envir = envir, + priority = rlang::arg_match(priority) + ) +} diff --git a/tests/testthat/test-options.R b/tests/testthat/test-options.R new file mode 100644 index 0000000..9250efa --- /dev/null +++ b/tests/testthat/test-options.R @@ -0,0 +1,8 @@ +test_that("locally setting options works", { + options::define_option("foo", default = "bar") + expect_equal(options::opt("foo"), "bar") + opt_set_local2("foo", "baz") + expect_equal(options::opt("foo"), "baz") + withr::deferred_run() + expect_equal(options::opt("foo"), "bar") +})