Skip to content

Commit

Permalink
Improve addition method
Browse files Browse the repository at this point in the history
Fixes #286
  • Loading branch information
hadley committed Jan 27, 2023
1 parent 794eb37 commit c478961
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 3 deletions.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
9 changes: 8 additions & 1 deletion R/glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/_snaps/glue.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
# + method requires character vectors

Code
as_glue("a") + 1
Error <simpleError>
RHS must be a character vector.
Code
1 + as_glue("a")
Error <simpleError>
LHS must be a character vector.

# unterminated comment

Code
Expand Down
12 changes: 10 additions & 2 deletions tests/testthat/test-glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Expand Down

0 comments on commit c478961

Please sign in to comment.