file_cache {filecacher}R Documentation

Gets or creates a cachem object for use with other functions.

Description

Gets or creates a cachem object for use with other functions.

Usage

file_cache(cache = NULL, type = NULL, ext_prefix = "cache_")

Arguments

cache

The path to an existing directory to use for caching.

If NULL (default) uses a folder called "cache" in the current path, using here::here(). The folder is created if it does not already exist.

Advanced: if an existing cachem object is provided, all other parameters are ignored and the object is passed on as is. This functionality is primarily used internally or for testing.

type

A string describing the type of cache. Must be NULL or one of 'rds', 'parquet', or 'csv'. If NULL (default), uses 'rds'.

ext_prefix

The prefix to use with the file extension, e.g. "cache_csv", instead of "csv".

Value

A cachem::cache_disk() object.

See Also

cachem::cache_disk()

Examples

# Create a temporary directory for the cache.
tf <- tempfile()
dir.create(tf)

# A dummy function that logs when it's called.
get_df <- function() {
  message("Getting df ...")
  return(mtcars)
}

# Use the resulting object in `with_cache()`.
# 1) The first time, the message is printed.
# 2) The second time, the object is pulled from the cache, with no message.
all.equal(with_cache(get_df(), "df", cache = tf), mtcars)
all.equal(with_cache(get_df(), "df", cache = tf), mtcars)

# `with_cache` is designed to be compatible with piping.
get_df() |>
  with_cache("df", cache = tf) |>
  all.equal(mtcars)


# Advanced: If desired, the `cachem` object methods can be used directly.
cache <- file_cache(tf)
cache$get("df") |> # Get objects previously cached using `with_cache`.
  all.equal(mtcars)
cache$set("df2", mtcars) # Set objects using `$set`.
cache$get("df2") |>
  all.equal(mtcars)

unlink(tf, recursive = TRUE)

[Package filecacher version 0.2.9 Index]