#' Conf Environment
#'
#' A Conf Environment Class.
#'
#'
#' @section Usage:
#' \preformatted{
#' Conf = ConfEnv$new(system.file("extdata/example.yml", package="rconf"))
#' Conf$configuration
#' Conf$getorstop("config")
#' Conf$getorstop("db.host")
#' Conf$getornull("config")
#' Conf$getornull("db.user")
#' }
#'
#' @section Arguments:
#' \code{filename} The filename of configuration file
#' \code{filetype} The filetype of configuration file values should be one of "" "yml", "json",
#' "ini", default is "" which autodetect filetype by file extension
#'
#' @section Methods:
#' \code{$new} Initialize a Conf interface
#' \code{$load} Load a configuration file
#' \code{$getornull} get value of configuration file by path, if does not exists return null.
#' the path is seperate by . as default. modify it by specify sep parameter.
#' \code{$getorstop} get value of configuration file by path, if does not exists stop program,
#' the path is seperate by . as default. modify it by specify sep parameter.
#' @name ConfEnv
NULL
#' @export
ConfEnv <- R6Class(
"Conf",
public=list(
filename = NULL,
filetype = "",
configuration = NULL,
initialize = function(filename=NA, filetype="") {
self$filename <- filename
self$load(filename = self$filename, filetype = self$filetype)
},
load=function(filename, filetype) {
private$setfiletype(filename, filetype)
self$configuration <- switch(
self$filetype,
yml = yaml::yaml.load_file(filename),
json = jsonlite::fromJSON(filename),
ini = ini::read.ini(filename)
)
invisible(0)
},
getornull=function(path, sep="\\.") {
if (is.null(self$configuration)) {
stop("please load configuration first")
}
return(self$getconf(self$configuration, path, sep))
},
getorstop = function(path, sep="\\.") {
if (is.null(self$configuration)) {
stop("please load configuration first")
}
value <- self$getconf(self$configuration, path, sep)
if (is.null(value)) {
stop("no such configuration")
}
return(value)
},
getconf=function(conflist, path, sep="\\.") {
p <- strsplit(path, sep)[[1]]
if (length(p) <= 1) {
p <- path
if (p %in% names(conflist)) {
return(list.extract(conflist, p))
}else{
return(NULL)
}
} else {
return(self$getconf(list.extract(conflist, p[1]), p[2]))
}
}
),
private=list(
setfiletype = function(filename, filetype) {
if (filetype != "" && filetype %in% c("ini", "yml", "json")) {
filetype <- filetype
}else if ( grepl("\\.ya*ml$", filename) ) {
filetype <- "yml"
}else if ( grepl("\\.json$", filename) ) {
filetype <- "json"
}else if ( grepl("\\.ini$", filename) ) {
filetype <- "ini"
}else{
stop("rconf only supports ya*ml, json, and ini.")
}
self$filetype <- filetype
}
)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.