File: cli_format_method.Rd

package info (click to toggle)
r-cran-cli 3.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: ansic: 16,412; cpp: 37; sh: 13; makefile: 2
file content (68 lines) | stat: -rw-r--r-- 2,072 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/print.R
\name{cli_format_method}
\alias{cli_format_method}
\title{Create a format method for an object using cli tools}
\usage{
cli_format_method(expr, theme = getOption("cli.theme"))
}
\arguments{
\item{expr}{Expression that calls \verb{cli_*} methods, \code{\link[base:cat]{base::cat()}} or
\code{\link[base:print]{base::print()}} to format an object's printout.}

\item{theme}{Theme to use for the formatting.}
}
\value{
Character vector, one element for each line of the printout.
}
\description{
This method can be typically used in \code{format()} S3 methods. Then the
\code{print()} method of the class can be easily defined in terms of such a
\code{format()} method. See examples below.
}
\examples{

# Let's create format and print methods for a new S3 class that
# represents the an installed R package: `r_package`

# An `r_package` will contain the DESCRIPTION metadata of the package
# and also its installation path.
new_r_package <- function(pkg) {
  tryCatch(
    desc <- packageDescription(pkg),
    warning = function(e) stop("Cannot find R package `", pkg, "`")
  )
  file <- dirname(attr(desc, "file"))
  if (basename(file) != pkg) file <- dirname(file)
  structure(
    list(desc = unclass(desc), lib = dirname(file)),
    class = "r_package"
  )
}

format.r_package <- function(x, ...) {
  cli_format_method({
    cli_h1("{.pkg {x$desc$Package}} {cli::symbol$line} {x$desc$Title}")
    cli_text("{x$desc$Description}")
    cli_ul(c(
      "Version: {x$desc$Version}",
      if (!is.null(x$desc$Maintainer)) "Maintainer: {x$desc$Maintainer}",
      "License: {x$desc$License}"
    ))
    if (!is.na(x$desc$URL)) cli_text("See more at {.url {x$desc$URL}}")
  })
}

# Now the print method is easy:
print.r_package <- function(x, ...) {
  cat(format(x, ...), sep = "\n")
}

# Try it out
new_r_package("cli")

# The formatting of the output depends on the current theme:
opt <- options(cli.theme = simple_theme())
print(new_r_package("cli"))
options(opt)  # <- restore theme
}