load_module: Load an R Script into a Managed Environment with Caching

View source: R/load_module.R

load_moduleR Documentation

Load an R Script into a Managed Environment with Caching

Description

Sources an R script into a new environment. The resolved, absolute file path is used as the unique identifier for caching. Subsequent calls for the same file path during the same R session will return the cached environment, avoiding re-sourcing.

Usage

load_module(file_path, parent_env = .GlobalEnv, refresh = FALSE)

Arguments

file_path

Character string: The path to the R script to load. Relative paths are resolved to an absolute path.

parent_env

The parent environment for the new environment created for the module's code. Defaults to .GlobalEnv.

refresh

Logical: If TRUE, forces the module to be reloaded and re-cached, even if it's already in the cache. Defaults to FALSE.

Value

An environment containing the objects created by sourcing file_path.

Examples

## Not run: 
  # Ensure your package is loaded if testing interactively, e.g., devtools::load_all()
  # or library(myutils) if installed.

  # Create a dummy R file for demonstration
  temp_r_file <- tempfile(fileext = ".R")
  # Ensure cleanup even if errors occur
  on.exit(unlink(temp_r_file, force = TRUE), add = TRUE)
  writeLines(c("message('Sourcing temp_r_file...')",
               "secret_value <- 42",
               "get_secret <- function() secret_value",
               "add_to_secret <- function(x) secret_value + x"), temp_r_file)

  # --- First load ---
  # (Will print 'Sourcing temp_r_file...')
  mod1 <- load_module(temp_r_file)
  print(paste("Value from mod1:", mod1$get_secret()))
  print(paste("Calculation from mod1:", mod1$add_to_secret(8)))

  # --- Second load (should be from cache) ---
  # (Should NOT print 'Sourcing temp_r_file...' again)
  mod2 <- load_module(temp_r_file) # Same file path, so uses cache
  stopifnot(identical(mod1, mod2)) # Should be the exact same environment object
  print("mod1 and mod2 are identical (from cache).")

  # --- Force refresh ---
  # (Will print 'Sourcing temp_r_file...' again)
  mod3 <- load_module(temp_r_file, refresh = TRUE)
  stopifnot(!identical(mod1, mod3)) # A new environment is created
  print(paste("Value from mod3 (refreshed):", mod3$get_secret()))
  print("mod1 and mod3 are NOT identical (refreshed).")

  # --- Test with a path that needs normalization (conceptual) ---
  # Create a file in a temporary subdirectory
  temp_dir <- file.path(tempdir(), "my_temp_module_dir")
  if (!dir.exists(temp_dir)) dir.create(temp_dir)
  on.exit(unlink(temp_dir, recursive = TRUE, force = TRUE), add = TRUE)

  file_in_subdir <- file.path(temp_dir, "another_mod.R")
  writeLines("message('Sourcing another_mod.R...'); module_var <- 'hello'", file_in_subdir)

  # Load using a relative path (if current dir allows) or modified path
  # This part of example assumes you might have paths like "./file.R" vs "file.R"
  # For simplicity, let's use the direct path and one that might be constructed
  mod_a <- load_module(file_in_subdir)

  # Construct a path that might look different but resolves to the same place
  # e.g., by adding redundant "./" if in that directory
  # For this example, we'll just use the same path again to show caching
  mod_b <- load_module(paste0(temp_dir, "/another_mod.R")) # Ensure same path format
  # A more robust test for normalization would involve relative paths like "."
  # if (file.exists("./temp_test_dir/another_mod.R")){
  #    mod_c <- load_module("./temp_test_dir/another_mod.R")
  #    stopifnot(identical(mod_a, mod_c))
  # }
  stopifnot(identical(mod_a, mod_b)) # Should be cached if paths normalize identically
  print("Normalized paths to the same file correctly use the cache.")

## End(Not run)

ChandlerLutz/CLmisc documentation built on June 9, 2025, 6:53 a.m.