[go: up one dir, main page]

Skip to content

Commit

Permalink
Ignore final empty argument (#329)
Browse files Browse the repository at this point in the history
* Ignore final empty argument

So you can use a trailing comma if you want. Fixes #320.

* Even nicer!

* Remove comment

---------

Co-authored-by: Jenny Bryan <jenny.f.bryan@gmail.com>
  • Loading branch information
hadley and jennybc authored Aug 21, 2024
1 parent 795f4c4 commit b5f1c05
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# glue (development version)

* `glue()` now drops the last argument if it's empty so that you can finish
each line with a comma if you want (#320).

* `glue_sql("{var*}")` once again generates `NULL` if var is empty.
This reverts #292. (#318).

Expand Down
19 changes: 7 additions & 12 deletions R/glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -107,24 +107,19 @@ glue_data <- function(.x, ..., .sep = "", .envir = parent.frame(),

# Capture unevaluated arguments
dots <- eval(substitute(alist(...)))

# Trim off last argument if its empty so you can use a trailing comma
n <- length(dots)
if (n > 0 && identical(dots[[n]], quote(expr = ))) {
dots <- dots[-n]
}
named <- has_names(dots)

# Evaluate named arguments, add results to environment
env <- bind_args(dots[named], parent_env)

# Concatenate unnamed arguments together
unnamed_args <- lapply(
which(!named),
function(x) {
# Any evaluation to `NULL` is replaced with `.null`:
# - If `.null == character()` then if any output's length is 0 the
# whole output should be forced to be `character(0)`.
# - If `.null == NULL` then it is allowed and any such argument will be
# silently dropped.
# - In other cases output is treated as it was evaluated to `.null`.
eval(call("force", as.symbol(paste0("..", x)))) %||% .null
}
)
unnamed_args <- lapply(which(!named), function(x) ...elt(x) %||% .null)
unnamed_args <- drop_null(unnamed_args)

if (length(unnamed_args) == 0) {
Expand Down
4 changes: 4 additions & 0 deletions tests/testthat/test-glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ test_that("glue errors if the expression fails", {
expect_error(glue("{NoTfOuNd}"), "object .* not found")
})

test_that("glue ignores trailing empty argument", {
expect_equal(glue("x", ), glue("x"))
})

test_that("glue errors if invalid format", {
expect_error(glue("x={x"), "Expecting '}'")
})
Expand Down

0 comments on commit b5f1c05

Please sign in to comment.