An open API service indexing awesome lists of open source software.

https://github.com/moodymudskipper/private

private closures for closures
https://github.com/moodymudskipper/private

Last synced: 25 days ago
JSON representation

private closures for closures

Awesome Lists containing this project

README

        

---
output: github_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```

# private

* Functions that are defined in the body of other functions cannot be tested easily
and clutter the body of the parent function, it's also not always clear if they use
lexical scoping or not
* If we move these functions to the namespace they make the codebase harder to
understand because we lose this relationship

{private} proposes a solution to these problems.

## Installation

Install with:

``` r
remotes::install_github("moodymudskipper/private")
```

## Example

```{r example}
library(private)
print_cubed <- function(x) {
x |> cube() |> format()
}
print_cubed %private% cube <- function(x) {x * square(x)}
# this works recursively
print_cubed %private% cube %private% square <- function(x) {x^2}
print_cubed %private% format <- function(x) {paste("Cubed value:", x)}

print_cubed(3)

# printing methods show the class, children and namespace
print_cubed

print_cubed %private% format

print_cubed %private% cube

print_cubed %private% cube %private% square

# private closures are not bound to the local environment (the namespace if we're in a package)
ls()

ls(environment(print_cubed))

ls(environment(print_cubed %private% cube))

# we can test the private methods
(print_cubed %private% cube)(4)
```

# Private S3 methods

Defining private S3 methods is straightforward

```{r, error = TRUE}
print_vec <- function(data) {
data <- as.character(data)
writeLines(sprintf("%s: %s", seq_along(data), data))
invisible(NULL)
}

print_vec %private% as.character.data.frame <-
function(x, ...) {stop("can't convert a data frame to a character")}
print_vec(letters[1:3])
print_vec(cars)
```