glue icon indicating copy to clipboard operation
glue copied to clipboard

Document how to write `glue()` wrappers

Open daattali opened this issue 2 years ago • 6 comments

I'm developing a package that uses a lot of glue. In each usage I want to use .trim = FALSE. It's very troublesome to add .trim = FALSE parameter to every glue call.

It would be wonderful to be able to set a global option for that, or for any other parameters (I also use .open = "{{" in every call).

daattali avatar Nov 03 '22 19:11 daattali

Write a wrapper function that does what you want?

jimhester avatar Dec 21 '22 20:12 jimhester

I did try that but unfortunately it doesn't work, at least not trivially, because of the environments in which it's called.

daattali avatar Dec 22 '22 06:12 daattali

For example:

myglue <- function(...) {
  glue::glue(..., .open = "{{", .close = "}}")
}

# this works
x <- 5
message(myglue("x: {{x}}"))

fxn <- function() {
  y <- 7
  # this doesn't work
  message(myglue("y: {{y}}"))
}
fxn()

daattali avatar Dec 22 '22 06:12 daattali

You need to wire up .envir in a wrapper function. Like so:

myglue <- function(..., .envir = parent.frame()) {
  glue::glue(..., .open = "{{", .close = "}}", .envir = .envir)
}

# this works
x <- 5
message(myglue("x: {{x}}"))
#> x: 5

fxn <- function() {
  y <- 7
  # this also works
  message(myglue("y: {{y}}"))
}
fxn()
#> y: 7

Created on 2022-12-22 with reprex v2.0.2.9000

jennybc avatar Dec 22 '22 16:12 jennybc

@jennybc I feel like an example of this pattern would be useful in the docs

DavisVaughan avatar Dec 23 '22 22:12 DavisVaughan

And improve the documentation for the .envir argument.

hadley avatar Jan 25 '23 22:01 hadley