use: Use a module as dependency

Description Usage Arguments Details Examples

View source: R/use.R

Description

Use and/or register a module as dependency. The behaviour of use is similar to import but instead of importing from packages, we import from a module. A module can be defined in a file, or be an object.

Usage

1
use(module, ..., attach = FALSE, reInit = TRUE, where = parent.frame())

Arguments

module

(character, module) a file or folder name, or an object that can be interpreted as a module: any list-like object would do.

...

(character, or unquoted expression) names to use from module.

attach

(logical) whether to attach the module to the search path.

reInit

(logical) we can use a module as is, or reinitialize it. The default is to reinitialize. This is only relevant should the module be state-full.

where

(environment) typically the calling environment. Should only be relevant for testing.

Details

import and use can replace library and attach. However they behave differently and are only designed to be used within modules. Both will work when called in the .GlobalEnv but here they should only be used for development and debugging of modules.

use adds a layer to a local search path if attach is TRUE. More precisely to the calling environment, which is the environment supplied by where. Regardless of the attach argument, use will return the module invisibly.

use supplies a special mechanism to find the argument module: generally you can supply a file name or folder name as character. You can also reference objects/names which 'live' outside the module scope. If names are not found within the scope of the module, they are searched for in the environment in which the module has been defined. This happens during initialization of the module, when the use function is called.

Modules can live in files. use should be used to load them. A module definition in a file does not need to use the module constructor explicitly. Any R script can be used as the body of a module.

When a folder is referenced in use it is transformed into a list of modules. This is represented as a nested list mimicking the folder structure. Each file in that folder becomes a module.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
m1 <- module({
  foo <- function() "foo"
})
m2 <- module({
  use(m1, attach = TRUE)
  bar <- function() "bar"
  m1foo <- function() foo()
})
m2$m1foo()
m2$bar()

## Not run: 
someFile <- tempfile(fileext = ".R")
writeLines("foo <- function() 'foo'", someFile)
m3 <- use(someFile)
m3$foo()
otherFile <- tempfile(fileext = ".R")
writeLines("bar <- function() 'bar'", otherFile)
m4 <- use(otherFile)
m4$bar()
m5 <- use(tempdir())
m5

## End(Not run)

modules documentation built on Feb. 7, 2021, 1:06 a.m.