Skip to content

Commit

Permalink
fix: Throw an error if template uses a parameter without a value
Browse files Browse the repository at this point in the history
Otherwise `glue::glue()` will just return an empty string.
This gives a much better and more focused error message.
  • Loading branch information
gadenbuie committed Jun 27, 2024
1 parent ab688ef commit fea04c5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
40 changes: 35 additions & 5 deletions R/app_json.R
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,10 @@ write_app_json <- function(
for (template_file in template_html_files) {
file_content <- brio::read_file(template_file)

file_content_interp <- glue::glue_data(
template_params,
file_content,
.open = "{{",
.close = "}}"
file_content_interp <- glue_template(
template = file_content,
params = template_params,
file = template_file
)

dest_file <- fs::path(app_destdir, fs::path_rel(template_file, html_source_dir))
Expand All @@ -213,3 +212,34 @@ write_app_json <- function(
)
verbose_print(": ", fs::file_info(app_json_output_file)$size[1], " bytes")
}

glue_template <- function(template, params, file = NULL) {
params <- list2env(params)
transformer <- glue_template_transformer(file)

glue::glue(
template,
.envir = params,
.open = "{{",
.close = "}}",
.na = "",
.null = "",
.transformer = transformer
)
}

glue_template_transformer <- function(file) {
function(text, envir) {
text <- trimws(text)

if (!exists(text, envir = envir)) {
rlang::abort(paste0(
"The template parameter `{{ ", text, " }}` was used ",
"in the export template in '", file, "', ",
"but a value was not provided to `template_params`."
))
}

get(text, envir = envir, inherits = FALSE)
}
}
19 changes: 19 additions & 0 deletions tests/testthat/test-app_json.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
test_that("glue_template() errors if template param is not defined", {
expect_snapshot(
glue_template("{{ not_defined }}", list(), "export_template/index.html"),
error = TRUE
)
})

test_that("glue_template() ignores unused parameters", {
expect_equal(
glue_template("{{ x }}", list(x = "a", y = "b"), "export_template/index.html"),
glue::glue("a")
)

expect_equal(
glue_template("{{ a }}{{ b }}", list(a = NULL, b = NA), "export_template/index.html"),
glue::glue("")
)
})

0 comments on commit fea04c5

Please sign in to comment.