Skip to contents

This function takes inspiration from withr::with_envvar() and may be useful for testing purposes.

Usage

with_config(
  config_yml,
  code,
  .active_config = c(R_CONFIG_ACTIVE = "default"),
  .extra_env_vars = NULL
)

Arguments

config_yml

Either the path to a config file, or a character string representing a yaml configuration.

code

Code to execute in a temporary environment.

.active_config

Either a string representing a configuration, e.g. default, or a named character representing an environment variable, e.g. c(R_CONFIG_ACTIVE = "default").

.extra_env_vars

Additional environment variables to set.

Value

The result of running the code, after having temporarily set the necessary environment variables.

Examples


yaml <- '
default:
  db_name: dbase
  databases:
    db1: !expr paste0(db_name, "/one")
    db2: !expr paste0(db_name, "/two")

staging:
  staging_postfix: _staging
  db_name: dbase
  databases:
    db1: !expr paste0(db_name, staging_postfix, "/one")
    db2: !expr paste0(db_name, staging_postfix, "/two")
'

# Ensure that base::get() doesn't get masked, for tests on CRAN
get <- base::get

with_config(yaml, config::get() )
#> $databases
#> $databases$db1
#> [1] "dbase/one"
#> 
#> $databases$db2
#> [1] "dbase/two"
#> 
#> 
#> $db_name
#> [1] "dbase"
#> 
with_config(yaml, config::get("databases", config = "default") )
#> $db1
#> [1] "dbase/one"
#> 
#> $db2
#> [1] "dbase/two"
#> 
with_config(yaml, config::get("databases", config = "staging") )
#> $db1
#> [1] "dbase_staging/one"
#> 
#> $db2
#> [1] "dbase_staging/two"
#> 

config_file <- system.file("tests/testthat/config.yml", package = "config")
if (file.exists(config_file)) {
  with_config(config_file, config::get())
}