Strict separation of settings from code.
configulaR is a port of the excellent python-decouple library for R.
Overview
As stated by its original author, configulaR makes it easy to:
- Store configuration parameters in ini or .env files
- Define comprehensive default values
- Properly convert values to the correct data type
- Have only one configuration module to rule all your application instances
configulaR’s behavior mimics python-decouple as closely as possible and is tested against python-decouple’s unit tests.
Installation
# Install from CRAN
install.packages("configulaR")
# Or install the development version from GitHub
# install.packages("devtools")
devtools::install_github("dataupsurge/configulaR")
How It Works
Usage
On-the-fly Parameter Evaluation
Parameter values can be retrieved anytime by invoking the configulaR::get_var
function:
library(configulaR)
# Retrieve a value from environment or config file
api_key <- get_var('API_KEY', default='my-default-key')
# With type casting
debug_mode <- get_var('DEBUG', default=FALSE, cast='logical')
port_number <- get_var('PORT', default=3000, cast='integer')
If the config
parameter is not provided, a config file search will be performed at each function call.
Preloading Config Files
To avoid repeated config file searches, preload the configuration once:
# Load config once
config <- get_config()
# Then use it for all subsequent calls
api_key <- get_var('API_KEY', config=config, default='my-default-key')
debug_mode <- get_var('DEBUG', config=config, default=FALSE, cast='logical')
Undefined Parameters
If a parameter has no default value and doesn’t exist in the environment or config files, configulaR will raise an error:
# This will fail if SECRET_KEY is not defined anywhere
secret_key <- get_var('SECRET_KEY')
# This will use the default if SECRET_KEY is not defined
secret_key <- get_var('SECRET_KEY', default='fallback-secret-key')
This fail-fast policy helps you avoid subtle bugs when parameters are missing.
Casting Argument
By default, all values returned by configulaR
are strings
.
To specify a different return type, use the cast
argument:
# Return as integer
max_connections <- get_var('MAX_CONNECTIONS', default='10', cast='integer')
# Return as logical
debug_enabled <- get_var('DEBUG', default='True', cast='logical')
# Return as float
timeout_seconds <- get_var('TIMEOUT', default='5.5', cast='float')
# Custom casting function
get_var('NUMBERS', default='1,2,3', cast=function(x) as.numeric(strsplit(x, ',')[[1]]))
Predefined casting types include:
- Integer:
'int'
,'integer'
- Boolean:
'bool'
,'boolean'
,'logical'
- Float:
'float'