Skip to contents

globally available storage

# this will create nested environments within in the global environment
rm.all()
local({
  order_id = "D1234"
  order <- storage_env("metayer", "menu", "dinner", order_id)
  order$chicken = TRUE

  meals <- storage_env("metayer", "menu")
  
  # assert that things are organized as we expect
  stopifnot(
    identical(order, meals$dinner[["D1234"]])
  )
  
  # return the order, an environment, cast as a list
  order %>%
    as.list()
})
$chicken
[1] TRUE

storage_env has a side effect, and this is by design. It creates a .storage container in the global environment. Subsequent calls to storage_env expect to have access to this hierarchical storage container.

# examine objects in the global enviroment
ls(all.names = TRUE)
[1] ".storage"
# access the order directly
.storage$metayer$menu$dinner$D1234 %>%
  as.list()
$chicken
[1] TRUE
# access the order through the api
storage_env("metayer", "menu", "dinner")$D1234 %>%
  as.list()
$chicken
[1] TRUE

locally scoped storage

It’s worth noting that the storage doesn’t have to live in the global namespace.

# Clean up the global environment, then create a 'lunch' container in the local environment.
rm.all()
local({
  order <- storage_env("metayer", "menu", "lunch", "L0222", .store = "lunch", .envir = current_env())
  order$burger = TRUE  

  # display a list of defined objects
  ls(all.names = TRUE) %>%
    capture.output() %>%
    cat()

  order %>% 
    as.list()
})
[1] "lunch" "order"
$burger
[1] TRUE

Here, storage_env is used in a way where the global environment is not polluted.

ls(all.names = TRUE) %>%
  is_empty()
[1] FALSE