From c47896182a8193f705faca9ac52e07c049bd8986 Mon Sep 17 00:00:00 2001 From: Hadley Wickham Date: Thu, 26 Jan 2023 18:09:54 -0600 Subject: [PATCH] Improve addition method Fixes #286 --- NEWS.md | 4 ++++ R/glue.R | 9 ++++++++- tests/testthat/_snaps/glue.md | 11 +++++++++++ tests/testthat/test-glue.R | 12 ++++++++++-- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index 374d5a01..fd5e5d03 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # glue (development version) +* `+` now works in more situations, and gives errors when one side isn't a + character vector. It no longer automatically applies glue interpolation to + both sides; you'll need to do that yourself as needed (#286). + * Add `$(C_VISIBILITY)` to compiler flags to hide internal symbols from the dll (#284 @lionel-). # glue 1.6.2 diff --git a/R/glue.R b/R/glue.R index 5df52b42..adb7a951 100644 --- a/R/glue.R +++ b/R/glue.R @@ -337,7 +337,14 @@ as.character.glue <- function(x, ...) { #' @export `+.glue` <- function(e1, e2) { - glue(e1, e2, .envir = parent.frame()) + if (!is.character(e1)) { + stop("LHS must be a character vector.") + } + if (!is.character(e2)) { + stop("RHS must be a character vector.") + } + + as_glue(paste0(e1, e2)) } #' @importFrom methods setOldClass diff --git a/tests/testthat/_snaps/glue.md b/tests/testthat/_snaps/glue.md index 58bbd230..72c7de7e 100644 --- a/tests/testthat/_snaps/glue.md +++ b/tests/testthat/_snaps/glue.md @@ -1,3 +1,14 @@ +# + method requires character vectors + + Code + as_glue("a") + 1 + Error + RHS must be a character vector. + Code + 1 + as_glue("a") + Error + LHS must be a character vector. + # unterminated comment Code diff --git a/tests/testthat/test-glue.R b/tests/testthat/test-glue.R index af9389da..f258ed96 100644 --- a/tests/testthat/test-glue.R +++ b/tests/testthat/test-glue.R @@ -509,9 +509,17 @@ test_that("throws informative error if interpolating a function", { test_that("+ method for glue works", { expect_identical(glue("foo") + "bar", as_glue("foobar")) + expect_identical(glue("x = ") + "{x}", as_glue("x = {x}")) - x <- 1 - expect_identical(glue("x = ") + "{x}", glue("x = {x}")) + x <- c("a", "b", "c") + expect_identical("(" + as_glue(x) + ")", paste0("(", x, ")")) +}) + +test_that("+ method requires character vectors", { + expect_snapshot(error = TRUE, { + as_glue("a") + 1 + 1 + as_glue("a") + }) }) test_that("unterminated quotes are error", {