From 94cca33aa9df447736fedd95c9ac2a43f56bd361 Mon Sep 17 00:00:00 2001 From: atusy <30277794+atusy@users.noreply.github.com> Date: Fri, 26 Apr 2024 23:43:02 +0900 Subject: [PATCH] feat(cache): allow pre/postprocessing cache objects --- R/cache.R | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/R/cache.R b/R/cache.R index 785dadcf0d..ee818c109f 100644 --- a/R/cache.R +++ b/R/cache.R @@ -32,7 +32,7 @@ new_cache = function() { # random seed is always load()ed keys = as.character(setdiff(keys, '.Random.seed')) envir = knit_global() - saveRDS(setNames(lapply(keys, function(k) envir[[k]]), keys), paste(path, 'rds', sep = '.')) + saveRDS(setNames(lapply(keys, function(k) knit_cache_preprocess(envir[[k]])), keys), paste(path, 'rds', sep = '.')) unlink(paste(path, c('rdb', 'rdx'), sep = '.')) # migrate from former implementation } @@ -65,7 +65,7 @@ new_cache = function() { envir = knit_global() obj = readRDS(paste(path, 'rds', sep = '.')) for (nm in names(obj)) { - assign(nm, obj[[nm]], envir = envir) + assign(nm, knit_cache_postprocess(obj[[nm]]), envir = envir) } } } @@ -142,6 +142,12 @@ cache_meta_name = function(hash) sprintf('.%s_meta', hash) # a variable name to store the text output of code chunks cache_output_name = function(hash) sprintf('.%s', hash) +# process cached objects before save and after read +knit_cache_preprocess = function(x, ...) UseMethod('knit_cache_preprocess') +knit_cache_preprocess.default = function(x, ...) x +knit_cache_postprocess = function(x, ...) UseMethod('knit_cache_postprocess') +knit_cache_postprocess.default = function(x, ...) x + cache = new_cache() # a regex for cache files