# set_project_env --------------------------------------------------------------
#
#' @title Set Project Options, Such as Paths, in a Designated Environment
#'
#' @description
#' GIVEN a path to a foler where a config.yml file exists and this file contains
#' a field named "options", WHEN \code{set_project_env} is called, THEN the
#' key-value pairs under "options" are evaluated and stored in an environment
#' named \code{.project}.
#'
#' @param path (`character`) A path to the project root folder where a
#' \code{config.yml} file exists.
#'
#' @examples
#' \donttest{
#' ## Create config.yml with a field named "options" and a variable named temp_path
#' yaml::write_yaml(x = list("options" = list(temp_path = "tempdir()")),
#' file = file.path(getwd(), "config.yml"))
#' ## Evaluate config.yml
#' set_project_env(path = getwd())
#' ## Check that temp_path is now available in the ".project" environment
#' all.equal(tempdir(), .project$temp_path)
#' }
#'
#' @seealso \code{\link[base]{options}}.
#'
#' @keywords internal
#' @export
#'
set_project_env <- function(path){
###########################
## Defensive Programming ##
###########################
## Check if config file exists
config_path <- file.path(path, "config.yml")
if(isFALSE(file.exists(config_path))) stop("Couldn't find ", path, "/config.yml")
## Check if "options" field exists
config_tags <- yaml::yaml.load_file(input = config_path)
if(is.null(config_tags$options)) stop("There is no 'options' field in ", path, "/config.yml")
###########
## Setup ##
###########
wd <- getwd()
on.exit(setwd(wd))
setwd(path)
## Load config file tags
config_tags <- yaml::yaml.load_file(input = config_path)
#######################
## Process YAML file ##
#######################
.create_project_env()
## Evaluate expressions
for(k in seq_along(config_tags$options)){
element_key <- names(config_tags$options)[[k]]
element_value <- config_tags$options[[k]]
element_value <- tryCatch(eval(parse(text = element_value)),
error = function(e) element_value)
assign(element_key, element_value, envir = .project)
}
############
## Return ##
############
return(invisible())
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.