klmr / box

Write reusable, composable and modular R code
https://klmr.me/box/
MIT License
829 stars 47 forks source link

Allow for python-like `if ("__main__")` pattern #296

Closed jtlandis closed 1 year ago

jtlandis commented 1 year ago

Please describe your feature request

I have found box as a useful package and I was curious if we could implement a function that would allow for certain R scripts to either run as an R script, or import exported functionality into another with box::use.

Since R doesn't have a mangling system like python, I imagine it would look something like



#' @export
execute_function <- function(...) {
 # ...
}

# only execute function if Rscript is called by command line
# otherwise, just make it available for module
if (is_rscript_exec(file_pattern = "My_script_name.R")) {
  execute_function(...)
}
klmr commented 1 year ago

That’s already implemented: box::name() corresponds to the current module name. You can use it as follows:

if (is.null(box::name())) {
    # only executed if the code is invoked as a script.
}