Transformers allow you to apply functions to the glue input and
output, before and after evaluation. This allows you to write things
like glue_sql()
, which automatically quotes variables for
you or add a syntax for automatically collapsing outputs.
The transformer functions simply take two arguments text
and envir
, where text
is the unparsed string
inside the glue block and envir
is the execution
environment. Most transformers will then call
eval(parse(text = text, keep.source = FALSE), envir)
which
parses and evaluates the code.
You can then supply the transformer function to glue with the
.transformer
argument. In this way users can manipulate the
text before parsing and change the output after evaluation.
It is often useful to write a glue()
wrapper function
which supplies a .transformer
to glue()
or
glue_data()
and potentially has additional arguments. One
important consideration when doing this is to include
.envir = parent.frame()
in the wrapper to ensure the
evaluation environment is correct.
Some example implementations of potentially useful transformers
follow. The aim right now is not to include most of these custom
functions within the glue
package. Rather, users are
encouraged to create custom functions using transformers to fit their
individual needs.
library(glue)
A transformer which automatically collapses any glue block ending
with *
.
<- function(regex = "[*]$", ...) {
collapse_transformer function(text, envir) {
<- grepl(regex, text)
collapse if (collapse) {
<- sub(regex, "", text)
text
}<- identity_transformer(text, envir)
res if (collapse) {
glue_collapse(res, ...)
else {
}
res
}
}
}
glue("{1:5*}\n{letters[1:5]*}", .transformer = collapse_transformer(sep = ", "))
#> 1, 2, 3, 4, 5
#> a, b, c, d, e
glue("{1:5*}\n{letters[1:5]*}", .transformer = collapse_transformer(sep = ", ", last = " and "))
#> 1, 2, 3, 4 and 5
#> a, b, c, d and e
<- c("one", "two")
x glue("{x}: {1:5*}", .transformer = collapse_transformer(sep = ", "))
#> one: 1, 2, 3, 4, 5
#> two: 1, 2, 3, 4, 5
A transformer which automatically quotes variables for use in shell
commands, e.g. via system()
or system2()
.
<- function(type = c("sh", "csh", "cmd", "cmd2")) {
shell_transformer <- match.arg(type)
type function(text, envir) {
<- eval(parse(text = text, keep.source = FALSE), envir)
res shQuote(res)
}
}
<- function(..., .envir = parent.frame(), .type = c("sh", "csh", "cmd", "cmd2")) {
glue_sh <- match.arg(.type)
.type glue(..., .envir = .envir, .transformer = shell_transformer(.type))
}
<- "test"
filename writeLines(con = filename, "hello!")
<- glue_sh("cat {filename}")
command
command#> cat 'test'
system(command)
A transformer which converts the text to the equivalent emoji.
<- function(text, envir) {
emoji_transformer if (grepl("[*]$", text)) {
<- sub("[*]$", "", text)
text glue_collapse(ji_find(text)$emoji)
else {
} ji(text)
}
}
<- function(..., .envir = parent.frame()) {
glue_ji glue(..., .open = ":", .close = ":", .envir = .envir, .transformer = emoji_transformer)
}glue_ji("one :heart:")
#> one ❤️
glue_ji("many :heart*:")
#> many 💘❤️💟💌
A transformer which allows succinct sprintf format strings.
<- function(text, envir) {
sprintf_transformer <- regexpr(":.+$", text)
m if (m != -1) {
<- substring(regmatches(text, m), 2)
format regmatches(text, m) <- ""
<- eval(parse(text = text, keep.source = FALSE), envir)
res do.call(sprintf, list(glue("%{format}"), res))
else {
} eval(parse(text = text, keep.source = FALSE), envir)
}
}
<- function(..., .envir = parent.frame()) {
glue_fmt glue(..., .transformer = sprintf_transformer, .envir = .envir)
}glue_fmt("π = {pi:.3f}")
#> π = 3.142
A transformer that acts like purrr::safely()
, which
returns a value instead of an error.
<- function(otherwise = NA) {
safely_transformer function(text, envir) {
tryCatch(
eval(parse(text = text, keep.source = FALSE), envir),
error = function(e) if (is.language(otherwise)) eval(otherwise) else otherwise)
}
}
<- function(..., .otherwise = NA, .envir = parent.frame()) {
glue_safely glue(..., .transformer = safely_transformer(.otherwise), .envir = .envir)
}
# Default returns missing if there is an error
glue_safely("foo: {xyz}")
#> foo: NA
# Or an empty string
glue_safely("foo: {xyz}", .otherwise = "Error")
#> foo: Error
# Or output the error message in red
library(crayon)
glue_safely("foo: {xyz}", .otherwise = quote(glue("{red}Error: {conditionMessage(e)}{reset}")))
#> foo: Error: object 'xyz' not found
A transformer that expands input of the form {var_name=}
into var_name = var_value
, i.e. a shorthand for exposing
variable names with their values. This is inspired by an f-strings
feature coming in Python 3.8. It’s actually more general: you can
use it with an expression input such as {expr=}
.
<- function(text, envir) {
vv_transformer <- "=$"
regex if (!grepl(regex, text)) {
return(identity_transformer(text, envir))
}
<- sub(regex, "", text)
text <- identity_transformer(text, envir)
res <- length(res)
n <- glue_collapse(res, sep = ", ")
res if (n > 1) {
<- c("[", res, "]")
res
}glue_collapse(c(text, " = ", res))
}
set.seed(1234)
<- "some random"
description <- sample(100, 4)
numbers <- mean(numbers)
average <- sum(numbers)
sum
glue("For {description} {numbers=}, {average=}, {sum=}.", .transformer = vv_transformer)
#> For some random numbers = [28, 80, 22, 9], average = 34.75, sum = 139.
<- 3
a <- 5.6
b glue("{a=}\n{b=}\n{a * 9 + b * 2=}", .transformer = vv_transformer)
#> a = 3
#> b = 5.6
#> a * 9 + b * 2 = 38.2