R/common_methods.R

storage_method  <- function(method = c("session","local","temp","custom"), local_path = ".store", store_function, fetch_function, clean_function){
  method <- match.arg(method)
  store_session("storage_method",method, internal = T)

  if(method == "local"){
    store_session("storage_method.local_path",local_path, internal = T)
  }

  if(method == "temp"){
    store_session("storage_method.temp_path",tempdir(), internal = T)
  }

  if(method == "custom"){
    store_session("storage_method.custom_store_function",store_function, internal = T)
    store_session("storage_method.custom_fetch_function",fetch_function, internal = T)
    if(missing(clean_function)){
      clean_function <- function(...){
        warning("no cleaning functions spplied")
      }
    }
    store_session("storage_method.custom_fetch_function",clean_function, internal = T)
  }

  invisible(0)

}

get_storage_method <- function(){
  fetch_session("storage_method", internal = T)
}

store <- function(key, value, group, local_path, ...){
  meth <- get_storage_method()

  if(is.null(meth)){
    warning("No storage method initiated. Initiating session store.")
    storage_method("session")
    return(invisible(-1))
  }

  switch(meth,
         session = {
           store_session(key, value, group)
         },
         local = {
           store_local(key, value, group, local_path)
         },
         temp = {
           store_local(key, value, group, local_path = fetch_session("storage_method.temp_path", internal = T))
         },
         custom = {
           c_s <- fetch_session("storage_method.custom_store_function", internal = T)
           if(is.function(c_s)){
             c_s(key, value, group, ...)
           }
         },
         {
           warning("Unknown storage method initiated. Initiating session store.")
           storage_method("session")
         })

}


fetch <- function(key, group, local_path, ...){

  meth <- get_storage_method()

  if(is.null(meth)){
    warning("No storage method initiated. Initiating session store.")
    storage_method("session")
    return(invisible(-1))
  }

  switch(meth,
         session = {
           fetch_session(key, group)
         },
         local = {
           fetch_local(key, group, local_path)
         },
         temp = {
           fetch_local(key, group, local_path = fetch_session("storage_method.temp_path", internal = T))
         },
         custom = {
           c_f <- fetch_session("storage_method.custom_fetch_function", internal = T)
           if(is.function(c_f)){
             c_f(key, group, ...)
           }
         },
         {
           warning("Unknown storage method initiated. Initiating session store.")
           storage_method("session")
         })

}
MadeInR/store documentation built on May 12, 2019, 8:41 a.m.