R/addHook.R

#' add a hook function to customize motusClient behaviour
#'
#' @param hookName character scalar hook hame; must be one of the names
#' in \code{names(Motus$hooks)}.  The name indicates the \code{motusClient} function
#' which is being customized.
#'
#' @param f function; the function must have the signature (rv, ...):
#' \enumerate{
#' \item rv the return value from the \code{motusClient} function if this
#' hook were not added.  The recommended behaviour is for \code{f} to return \code{rv}
#' unmodified.
#' \item ... the parameters accepted by the \code{motusClient} function given in hookname.
#' }
#'
#' @note: \link{\code{addHook()}} adds functions to the end of a hook, so the
#' functions on a hook are in order of being added, from earliest to latest.
#' You can get the list of functions on each hook by examining the global
#' variable \code{Motus$hooks}.
#'
#' @examples
#'
#' ## changing the .motus schema by creating a hook to ensure a .motus
#' ## database has a new table called 'myNewTable':
#'
#' # addHook("ensureDBTables",
#' #    function(rv, src, projRecv, deviceID) {
#' #      DBI::dbExecute(src$con, "CREATE TABLE IF NOT EXISTS myNewTable (motusTagID INTEGER PRIMARY KEY NOT NULL, userLabel TEXT)")
#' #      return(rv)
#' # })
#'
#' @return TRUE; if hookName is not valid, or f is not a function, or f accepts the wrong number
#' of parameters, then stops with an error
#'
#' @export
#'
#' @author John Brzustowski \email{jbrzusto@@REMOVE_THIS_PART_fastmail.fm}

addHook = function(hookName, f) {
    if (is.null(Motus$hooks[[hookName]]))
        stop("invalid hook name")
    if (!is.function(f))
        stop("`f` must be a function")
    fmls = formals(f)
    numFmls = 1 + length(formals(get(hookName)))
    if (length(fmls) != numFmls)
        stop("`f` has the wrong number of parameters; it should have ",  numFmls)
    if (names(fmls)[1] != "rv")
        stop("`f` the first parameter for f must be called `rv`")

    Motus$hooks[[hookName]] = c(Motus$hooks[[hookName]], f)
    return (TRUE)
}
jbrzusto/motusClient documentation built on May 30, 2019, 4:33 p.m.