#' Open an exercise
#'
#' Open an exercise file. A new file is created in your working directory unless
#' you specify the `dir` argument.
#'
#' @param number A number specifying which exercise to open.
#'
#' @param overwrite If you want to overwrite the exercise file you already
#' opened use overwrite = TRUE, default to `FALSE`.
#'
#' @param suffix If you do not want to overwrite your previous exercise file
#' but want to open another version you can specify text that will get
#' appended to the filename.
#'
#' For example, if `suffix` is `"attempt-2"` and `exercise` is 0 the new file
#' would be `exercise-0-attempt-2.R`.
#'
#' @param dir A character string specifying the directory where the exercise
#' file will be created, defaults to `getwd()`, the current working directory.
#'
#' @export
open_exercise <- function(number, overwrite = FALSE, suffix = NULL,
dir = getwd()) {
dir_exercises <- system.file("exercises", package = "zrsaSpatialWorkshop")
exercise_name <- paste("exercise", number, sep = "-")
exercise_file <- paste0(exercise_name, ".R")
if (Sys.getenv("RSTUDIO") == 1) {
editor <- rstudioapi::navigateToFile
} else {
editor <- file.edit
}
if (!file.exists(file.path(dir_exercises, exercise_file)) ||
number < 1 || number > 7) {
stop(
"could not find exercise number ", '"', number , '"',
call. = FALSE
)
}
path_exercise <- file.path(dir_exercises, exercise_file)
exercise_new <- paste(c(exercise_name, suffix), collapse = "-")
path_new <- file.path(dir, paste0(exercise_new, ".R"))
if (file.exists(path_new) && !isTRUE(overwrite)) {
editor(path_new)
stop(
"A file already exists for exercise ", number, ".",
"\n\n",
"If you want to overwrite this file please specify `overwrite = TRUE`.",
"\n\n",
"If you prefer to create a new exercise file you can specify `suffix`, ",
"see ?zrsaSpatialWorkshop::open_exercise",
call. = FALSE
)
}
file.copy(path_exercise, path_new, copy.mode = FALSE, overwrite = TRUE)
editor(path_new)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.