You can install the development version from GitHub with:
# install.packages("remotes")
remotes::install_github("rappster/pops")
Setting and getting custom options/settings for the packages you are developing.
I often (feel like I) need to store package specific “stuff” such as options/settings. and always came up with custom code in the various packages I developed -> trying to practice better “DRY”.
library(pops)
In your package’s .onLoad()
or .onAttach()
function you can call
init_package_options(<pkg_name>)
For example
.onLoad <- function(libname, pkgname) {
options(digits.secs = 3)
Sys.setenv(TZ = "UTC")
Sys.setenv(language = "en")
init_package_options(
pkg_name = pkgname,
values = list(hello = "world", devops_env = "staging")
)
invisible(TRUE)
}
As this function’s side effects will only materialize when you load an actual package, let’s try things out in a more direct manner.
If you are calling this within a package project (check by calling
pkg_name()
) then the following will work.
(Otherwise, just set pkg_name = "test"
in the following call to
init_package_options
).
init_package_options(values = list(hello = "world", devops_env = "staging"))
This created an “container environment” in your global options. It’s
either empty or in case you specified values
it will contain those
objects.
(option_env_name <- options() %>% names() %>% stringr::str_subset("__.__"))
#> [1] "__.__pops"
(option_env <- getOption(option_env_name))
#> <environment: 0x107986848>
option_env %>% ls()
#> [1] "devops_env" "hello"
option_env$hello
#> [1] "world"
There three convenience functions to get and set options/objects within the option environment
Return option values in a name-value list
get_options()
#> $devops_env
#> [1] "staging"
#>
#> $hello
#> [1] "world"
get_options(c("devops_env", "hello"))
#> $devops_env
#> [1] "staging"
#>
#> $hello
#> [1] "world"
get_options(c("hello"))
#> $hello
#> [1] "world"
Return option values
get_option("hello")
#> [1] "world"
Set option values
set_options(list(devops_env = "dev", foo = "bar"))
get_options()
#> $devops_env
#> [1] "dev"
#>
#> $foo
#> [1] "bar"
#>
#> $hello
#> [1] "world"