cl_yes_no_lgl: Ask Yes/No Questions via the console

Description Usage Arguments Details Value See Also Examples

View source: R/func_cli.R

Description

This function allows you to interact with a user by posing yes/no questions. It's inspired by usethis::ui_yeah(), and returns TRUE if the user responds affirmatively and FALSE if they respond negatively.

Usage

1
2
3
4
5
6
7
8
9
cl_yes_no_lgl(
  prompt,
  yes_opts = c("Yes", "Duh!", "Absolutely", "Please", "Obvi, yeah."),
  no_opts = c("No", "Nah", "Not now", "Not today", "No, thanks."),
  n_yes = 1,
  n_no = 2,
  shuffle = TRUE,
  .envir = parent.frame(1)
)

Arguments

prompt

A character string with the yes/no question to be asked. Passed into cli::cli_text() and can use its theming syntax.

yes_opts

A character vector of "yes" strings, randomly sampled to display to the user.

no_opts

A character vector of "no" strings, randomly sampled to display to the user.

n_yes

An integer defining how many "yes" strings to include when asking the user a question. Default is 1.

n_no

An integer defining how many "no" strings to include when asking the user a question. Default is 2.

shuffle

Logical: TRUE by default. Should the order of the yes/no options be shuffled before being presented to the user?

.envir

Used to ensure that cli::cli_text() evaluates the prompt, yes_message, and no_message in the appropriate environment. Expert use only.

Details

In general, I would recommend using cl_yes_no_action as it accepts code to execute depending on the user's response, but this function is perhaps more adaptable.

Value

Logical: TRUE if the user answers affirmatively and FALSE otherwise.

See Also

Other command-line-tools: cl_text_action(), cl_text_input(), cl_yes_no_action()

Examples

 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
if (interactive()) {

  # define a function to create a directory with approval.
  yn_create_dir <- function(path) {
    path <- here::here(path)
    if (cl_yes_no_lgl(prompt = "The directory {.file {path}} does not exist.
    Would you like to create it?")) {
      fs::dir_create(path)
    }
  }

  # Test the function
  yn_create_dir("new-folder")

  # Ask a simple yes/no question that prints a conditional response
  if (cl_yes_no_lgl(prompt = "Do you love sushi?")) print("Yay!")

  # Create a function that prints different answers depending on user response
  ask_about_tucker <- function() {

    # Simple yes/no with content-related yes/no options
    tucker_response <- cl_yes_no_lgl(prompt = "Is your favorite cat Tucker?",
                                     yes_opts = "Duh, he's the cutest",
                                     no_opts = c("I'm a dog person",
                                     "I'm allergic to cats"))

    if (tucker_response) print("Great answer!") else print("...")

  }

}

jdtrat/jdtools documentation built on Dec. 20, 2021, 10:05 p.m.