ctsit / redcapcustodian

Simplified, automated data management on REDCap systems
Other
13 stars 6 forks source link

Consider the use of zzz.R #40

Open ChemiKyle opened 2 years ago

ChemiKyle commented 2 years ago

See the end of this section of Hadley Wickham's guide on R packages.

Using zzz.R can let us handle some standard actions at the start and end of ETL executions, less boilerplate for ETLs. Here's a small sample zzz.R file:

# .onLoad is a reserved name in R
# these commands will be executed in the processing of library(redcapcustodian)
.onLoad <- function(libname, pkgname) {

  # insurance in case we don't explicitly write our boilerplate
  set_script_name()
  set_script_run_time()

  # suppressable message that will appear when library(redcapcustodian) is called
  packageStartupMessage(
    paste(
      "Executing:", get_script_name(),
      "at", get_script_run_time()
    )
  )

  # this does what you might think onUnload does
  # i.e. executes when the R script finishes
  reg.finalizer(
    stp.env,
    onSessionEnd,
    onexit = TRUE
  )
}

# not a reserved name, but will be executed when the R session finishes because we call it in reg.finalizer
onSessionEnd <- function(e) {

  print(
    paste("I am done running", get_script_name())
  )
}

Here's a small test script I wrote:

library(redcapcustodian)

print("mid script message")

And the output:

$ Rscript test.R
Executing: test.R at 2022-03-17 18:05:21
[1] "mid script message"
[1] "I am done running test.R"