diff --git a/NEWS.md b/NEWS.md index 335ced6..286a38f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,6 +3,7 @@ * Fixed an issue where disabling line statement could raise an error during template parsing. Since line statements are disabled by default, this error could be encountered quite easily (#31). * `quote_sql()` now escapes single-quotes using an additional single-quote (#30). * Fixed edge case in how error messages are formatted (#32). +* `render()` now validates data variables are supported (#25). # jinjar 0.3.0 diff --git a/R/encode.R b/R/encode.R index 8503066..465fc73 100644 --- a/R/encode.R +++ b/R/encode.R @@ -11,6 +11,18 @@ encode <- function(...) { )) } + for (name in names(data)) { + x <- data[[name]] + if (!(is_null(x) || is_logical(x) || is_integer(x) || is_double(x) || is_character(x) + || is_bare_list(x) || inherits_any(x, "data.frame"))) { + cli::cli_abort(c( + "Data variable {.arg {name}} is unsupported.", + "x" = "{.arg {name}} is {.obj_type_friendly {x}}.", + "i" = "Choices: NULL, logical, integer, double, character, list, dataframe." + )) + } + } + jsonlite::toJSON( data, auto_unbox = TRUE, # length-1 vectors output as scalars diff --git a/tests/testthat/_snaps/encode.md b/tests/testthat/_snaps/encode.md index e5d95a7..d34c729 100644 --- a/tests/testthat/_snaps/encode.md +++ b/tests/testthat/_snaps/encode.md @@ -16,3 +16,13 @@ ! All data variables must be named. x Unnamed variables: `b` and `mtcars` +# data validation works + + Code + encode(a = mean) + Condition + Error in `encode()`: + ! Data variable `a` is unsupported. + x `a` is a function. + i Choices: NULL, logical, integer, double, character, list, dataframe. + diff --git a/tests/testthat/test-encode.R b/tests/testthat/test-encode.R index a790732..0a14f16 100644 --- a/tests/testthat/test-encode.R +++ b/tests/testthat/test-encode.R @@ -6,3 +6,7 @@ test_that("dynamic dots work", { expect_equal(encode(a = 1), res) expect_equal(encode(!!!list(a = 1)), res) }) + +test_that("data validation works", { + expect_snapshot(encode(a = mean), error = TRUE) +})