#' Open the solution to an exercise
#'
#' Open a solution file. A new file is created in your working directory unless
#' you specify the `dir` argument.
#'
#' @param number A number specifying which solution to open.
#'
#' @param overwrite If you want to overwrite the solution file you already
#' opened use overwrite = TRUE, default to `FALSE`.
#'
#' @param suffix If you do not want to overwrite your previous solution 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 `solution` is 0 the new file
#' would be `solution-0-attempt-2.R`.
#'
#' @param dir A character string specifying the directory where the solution
#' file will be created, defaults to `getwd()`, the current working directory.
#'
#' @export
open_solution <- function(number, overwrite = FALSE, suffix = NULL,
dir = getwd()) {
dir_solutions <- system.file("solutions", package = "zrsaSpatialWorkshop")
solution_name <- paste("solution", number, sep = "-")
solution_file <- paste0(solution_name, ".R")
if (Sys.getenv("RSTUDIO") == 1) {
editor <- rstudioapi::navigateToFile
} else {
editor <- file.edit
}
if (!file.exists(file.path(dir_solutions, solution_file)) ||
number < 1 || number > 7) {
stop(
"could not find solution number ", '"', number , '"',
call. = FALSE
)
}
path_solution <- file.path(dir_solutions, solution_file)
solution_new <- paste(c(solution_name, suffix), collapse = "-")
path_new <- file.path(dir, paste0(solution_new, ".R"))
if (file.exists(path_new) && !isTRUE(overwrite)) {
editor(path_new)
stop(
"A file already exists for solution ", number, ".",
"\n\n",
"If you want to overwrite this file please specify `overwrite = TRUE`.",
"\n\n",
"If you prefer to create a new solution file you can specify `suffix`, ",
"see ?zrsaSpatialWorkshop::open_solution",
call. = FALSE
)
}
file.copy(path_solution, 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.