Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Init an article about wrapping glue #338

Merged
merged 7 commits into from
Aug 30, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions vignettes/wrappers.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
---
title: "How to write a function that wraps glue"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{How to write a function that wraps glue}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```

```{r setup}
library(glue)
```

Imagine that you want to call `glue()` repeatedly inside your own code (e.g. in your own package) with a non-default value for one or more arguments.
For example, maybe you anticipate producing R code where `{` and `}` have specific syntactic meaning.
Therefore, you'd prefer to use `<<` and `>>` as the opening and closing delimiters for expressions in `glue()`.

Spoiler alert: here's the correct way to write such a wrapper:

```{r}
my_glue <- function(..., .envir = parent.frame()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be worth a footnote pointing out that this is the same pattern you use in abort()/cli_abort() wrappers? And in defer()?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking the same! I added a sentence in the intro. I think it's worthy to point this out.

glue(..., .open = "<<", .close = ">>", .envir = .envir)
}
```

This is the key move:

> Include `.envir = parent.frame()` as an argument of the wrapper function and pass this `.envir` to the `.envir` argument of `glue()`.

If you'd like to understand why this is the way, keep reading.

## Working example

Here's an abbreviated excerpt of the roxygen comment that generates the documentation for the starwars dataset in dplyr:

```r
#' \describe{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example is much better!

#' \item{name}{Name of the character}
#' \item{height}{Height (cm)}
#' \item{mass}{Weight (kg)}
#' \item{species}{Name of species}
#' \item{films}{List of films the character appeared in}
#' }
```

To produce such text programmatically, the first step might be to generate the `\item` lines from a named list of column names and descriptions.
Notice that `{` and `}` are important to the `\describe{...}` syntax, so this is an example where it is nice for glue to use different delimiters for expressions.

Put the metadata in a suitable list:

```{r}
sw_meta <- list(
name = "Name of the character",
height = "Height (cm)",
mass = "Weight (kg)",
species = "Name of species",
films = "List of films the character appeared in"
)
```

Define a custom glue wrapper and use it inside another helper that generates `\item` entries[^1]:

[^1]: We're using `<@` and `@>` as the delimiters because this vignette is authored using R Markdown and knitr. The delimiters `<<` and ``>>` actually have special meaning in knitr, so it was easiest to use something else.
jennybc marked this conversation as resolved.
Show resolved Hide resolved

```{r}
my_glue = function(...) {
glue(..., .open = "<@", .close = "@>", .envir = parent.frame())
}

named_list_to_items <- function(x) {
my_glue("\\item{<@names(x)@>}{<@x@>}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that I think of it, is there a reason to not do just < and >?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would work in this exact example, but I don't want to model that in a vignette. I know some folks will copy exactly what they see here and I think < and > are too likely to collide with text in the template that should not get evaluated. Generally speaking.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about (( or [[? I'm just thinking that <@ looks hard to type.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well all of those come up a lot in real R code (like, the code you might want to evaluate) so again I shied away from them. It really sucks that you can't use <<. You can't even triple them <<< because that also matches knitr's regex (unintentionally, I think).

}
```

Apply `named_list_to_items()` to starwars metadata:

```{r}
named_list_to_items(sw_meta)
```

Here's how this would fail if we did *not* handle `.envir` correctly in our wrapper function:

```{r, error = TRUE}
my_glue_WRONG <- function(...) {
glue(..., .open = "<@", .close = "@>")
}

named_list_to_items_WRONG <- function(x) {
my_glue_WRONG("\\item{<@names(x)@>}{<@x@>}")
}

named_list_to_items_WRONG(sw_meta)
```

It can be hard to understand why `x` can't be found, when it is clearly available inside `named_list_to_items_WRONG()`.
Why isn't `x` available to `my_glue_WRONG()`?

## Where does `glue()` evaluate code?

What's going on?
It's time to look at the (redacted) signature of `glue()`:

```{r, eval = FALSE}
glue(..., .envir = parent.frame(), ...)
```

The expressions inside a glue string are evaluated with respect to `.envir`, which defaults to the environment where `glue()` is called from.

Everything is simple when evaluating `glue()` in the global environment.
jennybc marked this conversation as resolved.
Show resolved Hide resolved

```{r}
x <- 0
y <- 0
z <- 0

glue("{x} {y} {z}")
```

Now we wrap `glue()` in our own simple function, `myglue1()`.
Notice that `myglue()` doesn't capture its caller environment and pass that along.

When we execute `myglue1()` in the global environment, there's no obvious problem.

```{r}
myglue1 <- function(...) {
x <- 1
glue(...)
}

myglue1("{x} {y} {z}")
```

However, if we call our `myglue1()` inside another function, we see that all is not well.

```{r}
myglue2 <- function(...) {
x <- 2
y <- 2
myglue1(...)
}

myglue2("{x} {y} {z}")
```

Why do `x` and `y` not have the value 2?
Because `myglue1()` and its eventual call to `glue()` have no access to the execution environment of `myglue2()`.

If you want your glue wrapper to behave like `glue()` itself and to work as expected inside other functions, make sure it captures its caller environment and passes that along to `glue()`.

```{r}
myglue3 <- function(..., .envir = parent.frame()) {
x <- 3
glue(..., .envir = .envir)
}

myglue3("{x} {y} {z}")

myglue4 <- function(...) {
x <- 4
y <- 4
myglue3(...)
}

myglue4("{x} {y} {z}")
```
Loading