Skip to contents

Saves an R object to a user-specific directory on the local file system using a format inferred from the file extension. Supported formats include `.Rds`, `.json`, `.csv`, and `.lock`.

Usage

save_to_file(user_id, object, file_name, base_dir)

Arguments

user_id

A character string specifying the unique user ID.

object

The R object to save. This can be a list, data frame, atomic vector, or any serializable R object.

file_name

The name of the file to save, including its extension (e.g., `"account_tree.Rds"`, `"transactions.json"`, `"session.lock"`).

base_dir

The root directory where user-specific folders are stored. The object will be saved in `file.path(base_dir, user_id, file_name)`.

Value

Invisibly returns the path of the file after saving.

Details

This function serves as the `"file"` backend plugin for saving user data. It is usually called via `save_user_file()` and supports automatic directory creation for the target user.

The file format is determined from the extension in `file_name`: - **.Rds** — Saves the object using `saveRDS()`. - **.json** — Saves the object using `jsonlite::write_json()` with `auto_unbox = TRUE`. - **.csv** — Saves using `write.csv()` with `row.names = FALSE`. - **.lock** — Treated as a text file; `writeLines()` is used with the assumption that `object` is a string or scalar.

If the file extension is not recognized, the function falls back to serializing the object with `serialize()` and writes it as binary. A warning is issued to notify the developer and suggest extending the plugin to handle custom file types explicitly.

Note

This function is intended for internal use within the plugin system. For application-level usage, prefer calling `save_user_file()`.

See also

[save_user_file()], [load_from_file()], [build_plugin_args()]

Examples

if (FALSE) { # \dontrun{
save_to_file("user123", list(name = "Alice"), "profile.json",
             base_dir = "data")

save_to_file("user123", data.frame(income = c(100, 200)), "income.csv",
             base_dir = "data")

save_to_file("user123", MainAccount$new(name = "Main"), "account_tree.Rds",
             base_dir = "data")

# Save a lock file
save_to_file("user123", Sys.getpid(), "account_tree.lock",
             base_dir = "data")

# Save unknown file format (e.g., .yaml) — triggers warning
save_to_file("user123", list(config = TRUE), "custom.yaml",
             base_dir = "data")
} # }