R/zzz.R

Defines functions .onLoad .onAttach

.onAttach <- function(libname, pkgname) {
  version <- packageDescription(pkgname, fields = "Version")

  msg <- paste0("You are using ", pkgname, " version ", version)
  packageStartupMessage(msg)
  packageStartupMessage("Cache path: ", getOption("coco.cache_dir"))
  packageStartupMessage("Cache size: ", getOption("coco.cache_size"), " GB")
}

# Ref: https://r-pkgs.org/r.html
# https://www.r-bloggers.com/2021/07/caching-the-results-of-functions-of-your-r-package/
# https://community.rstudio.com/t/when-to-use-onload-vs-onattach/21953
.onLoad <- function(libname, pkgname) {
  # 热加载可能不支持,没试过

  cfile = app_sys("golem-config.yml")
  conf = yaml::read_yaml(cfile, eval.expr = FALSE)

  cache_size = conf$default$coco.cache_size
  cache_dir = conf$default$coco.cache_dir
  if (length(cache_size) != 1) {
    stop("cache size must set with a number in GB scale")
  }
  if (length(cache_dir) != 1) {
    stop("cache path must set with a directory")
  }
  if (grepl("\\(", cache_dir)) {
    cache_dir = eval(parse(text = cache_dir))
  }

  if (!is.null(cache_size)) {
    max_size = cache_size * 1024 ^ 3
  } else {
    max_size = 1024 * 1024^2
    cache_size = 2 / 1024
  }

  mm = cachem::cache_disk(cache_dir, max_size)
  options(coco.cache_dir = cache_dir, coco.cache_size = cache_size)

  database <<- memoise::memoise(database, cache = mm)

  cohorts <<- memoise::memoise(cohorts, cache = mm)
  cohort_ls <<- memoise::memoise(cohort_ls, cache = mm)

  datasets <<- memoise::memoise(datasets, cache = mm)
  dataset_info <<- memoise::memoise(dataset_info, cache = mm)
  dataset_load <<- memoise::memoise(dataset_load, cache = mm)
  dataset_query_idx <<- memoise::memoise(dataset_query_idx, cache = mm)

  invisible()
}
ShixiangWang/coco documentation built on July 9, 2022, 4:43 a.m.