Skip to content

Commit

Permalink
add local options helper
Browse files Browse the repository at this point in the history
  • Loading branch information
maxheld83 committed Jul 15, 2024
1 parent f47dfa5 commit d430626
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
7 changes: 4 additions & 3 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -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)
23 changes: 23 additions & 0 deletions R/options.R
Original file line number Diff line number Diff line change
@@ -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)
)
}
8 changes: 8 additions & 0 deletions tests/testthat/test-options.R
Original file line number Diff line number Diff line change
@@ -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")
})

0 comments on commit d430626

Please sign in to comment.