I work on an R package which wraps API calls. In order to reduce the number of actual calls and to speed things up, I memoise the function making the API call. To do so, I created the following function, which allows to set the cache directory:
memoise_fromJSON <- function(cache_dir = tempdir()) {
memoise::memoise(jsonlite::fromJSON,
cache = memoise::cache_filesystem(cache_dir))
}
To create the memoised function I use
memoised_fromJSON <- memoise_fromJSON()
Now, since I need the memoised function many times within my package, I would like to memoise the function at package startup. I tried
.onLoad <- function(libname, pkgname) {
memoised_fromJSON <- my_package:::memoise_fromJSON()
}
but I still need to run memoised_fromJSON <- memoise_fromJSON()
to get it to work.
So my questions are:
- Is there a possibility to memoise a function at package startup?
- If so, how can I memoise the function in a way that it is not visible in the global environment?
I guess, the questions are somehow related. Is my understanding correct that my attempt with .onLoad()
does not work because it creates the memoised function within the environment of .onLoad()
?
PS: I am aware, that I cannot change the cache_dir
at package loading, but I want to set a reasonable default which makes it possible to start without further ado. However, this keeps the possibility to change the cache directory if needed.